简体   繁体   English

在python类中列出@property装饰的方法

[英]list @property decorated methods in a python class

Is it possible to obtain a list of all @property decorated methods in a class? 是否可以获取类中所有@property装饰方法的列表? 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? 我如何从此类中获得['foo', 'bar']

Anything decorated with property leaves a dedicated object in your class namespace. 任何用property修饰的东西都会在类名称空间中留下一个专用对象。 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: 查看类的__dict__ ,或使用vars()函数获得相同的值,并且作为property类型实例的任何值都是匹配项:

[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). 请注意,这将包括直接使用property() (实际上是装饰器所做的事情),并且名称的顺序是任意的(因为字典没有设置顺序)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM