List @property styled methods in python class

Is it possible to get a list of all @propertydecorated methods in a class? If so, how?

Example:

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

How to get ['foo', 'bar']from this class?

+4
source share
1 answer

Everything that is decorated propertyleaves the selected object in the class namespace. Look at the __dict__class or use a function vars()to get the same thing, and any value that is an instance of the type propertymatches:

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

, , property() ( , ) ( ).

+7

All Articles