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

时间:2020-08-04 16:11:26

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

尽管var1ChildClass类的成员,但为什么我不能使用var1访问ChildClass.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'

谢谢

1 个答案:

答案 0 :(得分:2)

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

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