在Python对象中,如何查看已使用@property装饰器定义的属性列表?

Kyl*_*ild 15 python python-2.6 python-2.7

我可以看到使用的第一类成员变量self.__dict__,但是我也希望看到一个属性字典,如@property装饰器所定义的那样.我怎样才能做到这一点?

And*_*ark 17

您可以在类中添加一个看起来像这样的函数:

def properties(self):
    class_items = self.__class__.__dict__.iteritems()
    return dict((k, getattr(self, k)) 
                for k, v in class_items 
                if isinstance(v, property))
Run Code Online (Sandbox Code Playgroud)

这将查找类中的任何属性,然后创建一个字典,其中包含具有当前实例值的每个属性的条目.

  • 请注意,这仅列出了类IIRC上声明的属性.不会列出超类的属性. (2认同)
  • 你可以走自己.__ class __.mro()来找到父类. (2认同)
  • 对于 python 3,将 iteritems() 替换为 items() (2认同)

Joh*_*ooy 5

属性是类的一部分,而不是实例。所以你需要查看self.__class__.__dict__或等效vars(type(self))

所以属性将是

[k for k, v in vars(type(self)).items() if isinstance(v, property)]
Run Code Online (Sandbox Code Playgroud)