How to access properties of Python super classes e.g. via __class__.__dict__?

后端 未结 2 372
鱼传尺愫
鱼传尺愫 2020-12-19 04:21

How can I get all property names of a python class including those properties inherited from super classes?

class A(object):
  def getX(self         


        
相关标签:
2条回答
  • 2020-12-19 04:52

    You can either use "dir", or you can follow all the classes that are contained in the tuple returned by "mro" (method resolution order,given by the __mro__ attribute on the class) - this later method is the only way of uncovering attributes that where later overriden 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)
    >>> 
    
    0 讨论(0)
  • 2020-12-19 04:56

    You can use dir():

    for attr_name in dir(B):
        attr = getattr(B, attr_name)
        if isinstance(attr, property):
            print attr
    
    0 讨论(0)
提交回复
热议问题