在Python对象中,如何查看使用@property装饰器定义的属性列表?
我可以通过 self.__dict__
查看类里面的普通成员变量,但我也想看到用 @property 装饰器定义的属性字典。我该怎么做呢?
5 个回答
4
正如user2357112-supports-monica在对一个重复问题的评论中提到的,之前的答案只获取了直接在类中定义的属性,忽略了继承来的属性。为了修复这个问题,我们还需要查看父类的属性:
from typing import List
def own_properties(cls: type) -> List[str]:
return [
key
for key, value in cls.__dict__.items()
if isinstance(value, property)
]
def properties(cls: type) -> List[str]:
props = []
for kls in cls.mro():
props += own_properties(kls)
return props
举个例子:
class GrandparentClass:
@property
def grandparent_prop(self):
return "grandparent_prop"
class ParentClass(GrandparentClass):
@property
def parent_prop(self):
return "parent"
class ChildClass(ParentClass):
@property
def child_prop(self):
return "child"
properties(ChildClass) # ['child_prop', 'parent_prop', 'grandparent_prop']
如果你想获取一个实例的属性,只需将instance.__class__
传给get_properties
函数即可。
8
这些属性是属于类的,而不是属于某个具体的实例。所以你需要查看 self.__class__.__dict__
,或者用 vars(type(self))
也可以。
这样你就能看到这些属性了。
[k for k, v in vars(type(self)).items() if isinstance(v, property)]
21
你可以在你的类里添加一个函数,像这样:
def properties(self):
# class_items = self.__class__.__dict__.iteritems() # Python 2
class_items = self.__class__.__dict__.items()
return dict((k, getattr(self, k))
for k, v in class_items
if isinstance(v, property))
这个函数会检查类里面的所有属性,然后为每个属性创建一个字典,字典里的每一项都对应着当前实例的值。