Class properties without superclass properties

I have an inheritance hierarchy in which some of the classes have a class property, such as pickled. I would like to get A.pickledif it exists, or None if not, even if A comes from many classes, including, for example, B and B.pickled(or not).

Now my solution is scanning A __mro__. I would like, if possible, a cleaner solution.

+1
source share
2 answers

To get around a normal search through __mro__, look directly at the class attribute dictionary. You can use the vars()function for this:

return vars(cls).get('pickled', None)

__dict__:

return cls.__dict__.get('pickled', None)

.

object.__getattribute__ - ; . .__ getattribute__ .__ getattribute__?

type.__getattribute__ - , , MRO.

+2

, , ,

try:
    return object.__getattribute__(cls, 'pickled')
except AttributeError:
    return None
0

Source: https://habr.com/ru/post/1544056/


All Articles