Search code examples
pythoninheritancepython-2.xmetaclassgetattribute

How can we access inherited class attributes in case of metaclasses


Even though var1 is a member of the ChildClass class, why am i not able to access var1 using 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

I am getting the following error

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

Thanks


Solution

  • Since MyType is a type, use type.__getattribute__ instead of object.__getattribute__:

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