Class properties without superclass properties

2019-08-09 20:02发布

问题:

I have an inheritance hierarchy whereby some of the classes have a class property named e.g., 'pickled'. I would like to get A.pickled if it exists or None if not — even if A derives from many classes including e.g., B and B.pickled exists (or not).

Right now my solution crawls A's __mro__. I would like a cleaner solution if possible.

回答1:

To bypass the normal search through the __mro__, look directly at the attribute dictionary of the class instead. You can use the vars() function for that:

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

You could just access the __dict__ attribute directly too:

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

but using built-in functions is preferred over direct access to the double-underscored attribute dictionary.

object.__getattribute__ is the wrong method to use for looking at class attributes; see What is the difference between type.__getattribute__ and object.__getattribute__?

type.__getattribute__ is what is used for attribute access on classes, but that'd still search the MRO too.



回答2:

I'm not sure, but perhaps

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