This is a simplified example of my actual problem.
I have a class foo
defined like this in foo.py
:
class foo(object):
def __init__(self):
pass
def bar(self):
return True
@property
def baz(self):
return False
Now, I want to use the inspect
module to get the methods of the foo
class (including baz
). This is what I have so far in getmethods.py
:
import foo
import inspect
classes = inspect.getmembers(foo, inspect.isclass)
for cls in classes:
methods = inspect.getmembers(cls[1], inspect.ismethod)
print methods
When I run this script, I get the following output (which isn't exactly unexpected):
[('__init__', <unbound method foo.__init__>), ('bar', <unbound method foo.bar>)]
So, my question is, why exactly is baz
not considered a method and how can I modify getmethods.py
to get the following output:
[('__init__', <unbound method foo.__init__>), ('bar', <unbound method foo.bar>), ('baz', <property object at 0x7fbc1a73d260>)]
The @property is a built-in decorator for the property() function in Python. It is used to give "special" functionality to certain methods to make them act as getters, setters, or deleters when we define properties in a class.
The @property Decorator In Python, property() is a built-in function that creates and returns a property object. The syntax of this function is: property(fget=None, fset=None, fdel=None, doc=None) where, fget is function to get value of the attribute. fset is function to set value of the attribute.
There is the dir(theobject) method to list all the fields and methods of your object (as a tuple) and the inspect module (as codeape write) to list the fields and methods with their doc (in """). Because everything (even fields) might be called in Python, I'm not sure there is a built-in function to list only methods.
The simplest way to get a list of methods of any object is to use the help() command. It will list out all the available/important methods associated with that object.
The @property
decorator produces a property
object, not a function or a method. It is this object that calls the function it has stored in the .fget
, .fset
and .fdel
attributes on that object when accessed (through the descriptor protocol).
You'll have to explicitly test for that object type:
methods = inspect.getmembers(cls[1], inspect.ismethod)
properties = inspect.getmembers(cls[1], lambda o: isinstance(o, property))
or
methods_and_properties = inspect.getmembers(
cls[1], lambda o: isinstance(o, (property, types.MethodType)))
Note that the same limitations apply to classmethod
and staticmethod
objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With