我可以使用 来查看一流的成员变量self.__dict__
,但我还想查看使用@property装饰器定义的属性字典。我怎样才能做到这一点?
问问题
3326 次
5 回答
19
您可以向您的类添加一个看起来像这样的函数:
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))
这会查找类中的任何属性,然后创建一个字典,其中包含具有当前实例值的每个属性的条目。
于 2011-05-03T22:01:20.050 回答
6
属性是类的一部分,而不是实例。因此,您需要查看self.__class__.__dict__
或等效地查看vars(type(self))
所以属性将是
[k for k, v in vars(type(self)).items() if isinstance(v, property)]
于 2011-05-03T21:59:53.250 回答
2
对于对象 f,这给出了作为属性的成员列表:
[n for n in dir(f) if isinstance(getattr(f.__class__, n), property)]
于 2011-05-03T22:09:35.210 回答
2
正如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
于 2021-01-21T10:23:57.380 回答
-1
dir(obj)
给出 的所有属性的列表obj
,包括方法和属性.
于 2011-05-03T21:46:37.037 回答