列出 Python 类中的 @property 装饰方法 [英] list @property decorated methods in a python class
问题描述
是否可以获得类中所有 @property
修饰方法的列表?如果是这样怎么办?
示例:
class MyClass(object):@财产def foo(self):经过@财产定义栏(自我):经过
我如何从这个类中获取['foo', 'bar']
?
任何用 property
修饰的东西都会在你的类命名空间中留下一个专用对象.查看类的__dict__
,或者使用vars()
函数获取相同的,以及任何作为属性
类型匹配:
[name for name, value in vars(MyClass).items() if isinstance(value, property)]
演示:
<预><代码>>>>类我的类(对象):... @财产... def foo(self):... 经过... @财产...定义栏(自我):... 经过...>>>变量(我的类)dict_proxy({'__module__': '__main__', 'bar': <property object at 0x1006620a8>, '__dict__': <attribute '__dict__' of 'MyClass' objects>, 'foo': <property object at 0x1006620a8>;, '__weakref__': <'MyClass' 对象的属性 '__weakref__', '__doc__': None})>>>[名称的名称,vars(MyClass).items() 中的值如果 isinstance(value, property)]['bar', 'foo']请注意,这将包括任何直接使用 property()
的内容(这就是装饰器所做的,真的),并且名称的顺序是任意的(因为字典没有固定顺序).
Is it possible to obtain a list of all @property
decorated methods in a class? If so how?
Example:
class MyClass(object):
@property
def foo(self):
pass
@property
def bar(self):
pass
How would I obtain ['foo', 'bar']
from this class?
Anything decorated with property
leaves a dedicated object in your class namespace. Look at the __dict__
of the class, or use the vars()
function to obtain the same, and any value that is an instance of the property
type is a match:
[name for name, value in vars(MyClass).items() if isinstance(value, property)]
Demo:
>>> class MyClass(object):
... @property
... def foo(self):
... pass
... @property
... def bar(self):
... pass
...
>>> vars(MyClass)
dict_proxy({'__module__': '__main__', 'bar': <property object at 0x1006620a8>, '__dict__': <attribute '__dict__' of 'MyClass' objects>, 'foo': <property object at 0x100662050>, '__weakref__': <attribute '__weakref__' of 'MyClass' objects>, '__doc__': None})
>>> [name for name, value in vars(MyClass).items() if isinstance(value, property)]
['bar', 'foo']
Note that this will include anything that used property()
directly (which is what a decorator does, really), and that the order of the names is arbitrary (as dictionaries have no set order).
这篇关于列出 Python 类中的 @property 装饰方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!