在python类中列出@property装饰的方法 [英] list @property decorated methods in a python class

查看:152
本文介绍了在python类中列出@property装饰的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以获取类中所有 @property 装饰方法的列表?

Is it possible to obtain a list of all @property decorated methods in a class? If so how?

示例:

class MyClass(object):
    @property
    def foo(self):
        pass
    @property
    def bar(self):
        pass

如何从中获取 ['foo','bar']

推荐答案

任何装饰有属性的东西都会在您的计算机中留下一个专用对象类名称空间。查看该类的 __ dict __ ,或使用 vars()函数获取该值以及任何是属性类型的实例是匹配项:

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)]

演示:

>>> 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']

请注意,这将包括直接使用 property()的任何东西(实际上是装饰器所做的) ,并且名称的顺序是任意的(因为字典没有固定顺序)。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆