Class properties without superclass properties

心不动则不痛 提交于 2019-12-24 12:21:52

问题


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


来源:https://stackoverflow.com/questions/24150636/class-properties-without-superclass-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!