在 Python 对象中,如何查看已使用 @property 装饰器定义的属性列表?
问题描述:
我可以使用 self.__dict__
查看一流的成员变量,但我还想查看使用 @property 装饰器.我该怎么做?
I can see first-class member variables using self.__dict__
, but I'd like also to see a dictionary of properties, as defined with the @property decorator. How can I do this?
答
您可以向类中添加如下所示的函数:
You could add a function to your class that looks something like this:
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))
这会查找类中的所有属性,然后为每个属性创建一个字典,其中包含当前实例值的每个属性.
This looks for any properties in the class and then creates a dictionary with an entry for each property with the current instance's value.