[英]Get all the decorated properties of a class
I have a class that looks like: 我有一堂课,看起来像:
class Test(object):
@property
def prop1(self):
return 5
@property
def prop2(self):
return 10
How do I get back the properties I implemented? 如何获取实现的属性? For example,
[prop1, prop2]
. 例如,
[prop1, prop2]
。
I have tried vars()
and dir()
but these seem to also return hidden/special methods. 我试过
vars()
和dir()
但是这些似乎还返回隐藏/特殊方法。
Is the only way to do this to parse through the results that don't have underscores for say dir()
? 是这样做的唯一方法来解析没有
dir()
下划线的结果吗?
Try this 尝试这个
>>>[ k for k,v in Test.__dict__.items() if isinstance(v, property) ]
['prop1', 'prop2']
Since property is a type we can use isinstance
to find it in the class' internal dictionary. 由于property是一种类型,我们可以使用
isinstance
在类的内部字典中找到它。
You can use following: 您可以使用以下内容:
def isprop(v):
return isinstance(v, property)
propnames = [name for (name, value) in inspect.getmembers(Test, isprop)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.