在 metaclasses 的情况下,我们如何访问继承的 class 属性

How can we access inherited class attributes in case of metaclasses

即使 var1ChildClass class 的成员,为什么我无法使用 ChildClass.var1[=17= 访问 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'

谢谢

因为 MyTypetype,所以使用 type.__getattribute__ 而不是 object.__getattribute__:

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