【问题标题】:How can we access inherited class attributes in case of metaclasses在元类的情况下,我们如何访问继承的类属性
【发布时间】:2020-11-24 18:52:17
【问题描述】:

即使var1ChildClass 类的成员,为什么我无法使用ChildClass.var1 访问var1

class MyType(type):
    def __getattribute__(self, name):
        print('attr lookup for %s' % str(name))
        return object.__getattribute__(self, name)
class BaseClass(object):
    __metaclass__ = MyType
    var1 = 5
class ChildClass(BaseClass):
    var2 = 6
print(ChildClass.var2) #works
print(ChildClass.var1) #fails

我收到以下错误

AttributeError: 'MyType' object has no attribute 'var1'

谢谢

【问题讨论】:

  • 你为什么使用 Python 2?

标签: python inheritance python-2.x metaclass getattribute


【解决方案1】:

由于MyTypetype,请使用type.__getattribute__ 而不是object.__getattribute__

class MyType(type):
    def __getattribute__(self, name):
        print('attr lookup for %s' % str(name))
        return type.__getattribute__(self, name)

【讨论】: