How to access properties of Python superclasses, for example. via __class __.__ dict__?

How to get all python class property names , including properties inherited from superclasses ?

class A(object): def getX(self): return "X" x = property(getX) a = A() ax 'X' class B(A): y = 10 b = B() bx 'X' a.__class__.__dict__.items() [('__module__', '__main__'), ('getX', <function getX at 0xf05500>), ('__dict__', <attribute '__dict__' of 'A' objects>), ('x', <property object at 0x114bba8>), ('__weakref__', <attribute '__weakref__' of 'A' objects>), ('__doc__', None)] b.__class__.__dict__.items() [('y', 10), ('__module__', '__main__'), ('__doc__', None)] 

How can I access end-to-end b properties? Need: "Give me a list of all the property names from b, including those that are inherited from!"

 >>> [q for q in a.__class__.__dict__.items() if type(q[1]) == property] [('x', <property object at 0x114bba8>)] >>> [q for q in b.__class__.__dict__.items() if type(q[1]) == property] [] 

I want to get results from the first (a) when I work with the second (b), but the current one can only get an empty list. This should also work for another C inherited from B.

+5
source share
2 answers

You can use dir() :

 for attr_name in dir(B): attr = getattr(B, attr_name) if isinstance(attr, property): print attr 
+3
source

You can use "dir", or you can follow all the classes that are contained in the tuple returned by "mro" (the method resolution order specified by the __mro__ attribute in the class) - this later method is the only way to expand attributes that are later overridden by subclasses:

 >>> class A(object): ... b = 0 ... >>> class B(A): ... b = 1 ... >>> for cls in B.__mro__: ... for item in cls.__dict__.items(): ... if item[0][:2] != "__": ... print cls.__name__, item ... B ('b', 1) A ('b', 0) >>> 
+1
source

All Articles