How to access a superclass's class attributes in Python?

Posted by Brecht Machiels on Stack Overflow See other posts from Stack Overflow or by Brecht Machiels
Published on 2011-01-05T20:41:49Z Indexed on 2011/01/05 20:54 UTC
Read the original article Hit count: 291

Filed under:
|
|

Have a look at the following code:

class A(object):
    defaults = {'a': 1}

    def __getattr__(self, name):
        print('A.__getattr__')
        return self.get_default(name)

    @classmethod
    def get_default(cls, name):
        # some debug output
        print('A.get_default({}) - {}'.format(name, cls))
        try:
            print(super(cls, cls).defaults) # as expected
        except AttributeError: #except for the base object class, of course
            pass

        # the actual function body
        try:
            return cls.defaults[name]
        except KeyError:
            return super(cls, cls).get_default(name) # infinite recursion
            #return cls.__mro__[1].get_default(name) # this works, though

class B(A):
    defaults = {'b': 2}

class C(B):
    defaults = {'c': 3}


c = C()
print('c.a =', c.a)

I have a hierarchy of classes each with its own dictionary containing some default values. If an instance of a class doesn't have a particular attribute, a default value for it should be returned instead. If no default value for the attribute is contained in the current class's defaults dictionary, the superclass's defaults dictionary should be searched.

I'm trying to implement this using the recursive class method get_default. The program gets stuck in an infinite recursion, unfortunately. My understanding of super() is obviously lacking. By accessing __mro__, I can get it to work properly though, but I'm not sure this is a proper solution.

I have the feeling the answer is somewhere in this article, but I haven't been able to find it yet. Perhaps I need to resort to using a metaclass?

© Stack Overflow or respective owner

Related posts about python

Related posts about super