在 Python 对象中,如何查看已使用 @property 装饰器定义的属性列表? [英] In a Python object, how can I see a list of properties that have been defined with the @property decorator?
本文介绍了在 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.
这篇关于在 Python 对象中,如何查看已使用 @property 装饰器定义的属性列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文