枚举Python类属性(不是函数)

时间:2014-01-30 14:41:31

标签: python python-2.7 properties attributes enumerate

如何枚举标有@property

的Python类的函数
class MyClass:
    @property
    def my_property():
        pass

像这样,但inspect.isproperty没有lambda过滤器:

properties = inspect.getmembers(obj, inspect.isproperty)

显然,这些被称为托管属性。

1 个答案:

答案 0 :(得分:3)

这样做:

inspect.getmembers(obj.__class__, lambda x: isinstance(x, property))

以下是它的工作原理(使用IPython):

In [29]: class Foo(object):
   ....:     @property
   ....:     def foo(self): return 42
   ....:     

In [30]: obj = Foo()

In [31]: inspect.getmembers(obj.__class__, lambda prop: isinstance(prop, property))
Out[31]: [('foo', <property at 0x106aec6d8>)]

这是有效的,因为property确实是一个普通的(新式)类;通过使用@property标记内容,您只需创建property的实例。这也意味着可以使用property将属性的实例(在类上)与isinstance进行类型比较。

相关问题