Is it possible to get a list of class's methods and then invoke the methods on an instance of the class? I have come across code that makes a list of a class's methods, but I haven't found an example that also invokes the methods on an instance of the class.
Given the class:
class Test:
def methodOne(self):
print 'Executed method one'
def methodTwo(self):
print 'Executed method two'
And you make a list of the class's methods:
import inspect
a = Test()
methodList = [n for n, v in inspect.getmembers(a, inspect.ismethod)]
I would like to invoke every method in the methodList
on an instance of the class, like:
for method in methodList:
a.method()
The result would be equivalent to:
a.methodOne()
a.methodTwo()
Use getattr(a,methodname)
to access the actual method, given the string name, methodname
:
import inspect
import types
class Test(object):
def methodOne(self):
print('one')
def methodTwo(self):
print('two')
a = Test()
methodList = [n for n, v in inspect.getmembers(a, inspect.ismethod)
if isinstance(v,types.MethodType)]
for methodname in methodList:
func=getattr(a,methodname)
func()
yields
one
two
As Jochen Ritzel points out, if you are more interested in the actual methods (callable objects) than the method names (strings), then you should change the definition of methodList
to
methodList = [v for n, v in inspect.getmembers(a, inspect.ismethod)
if isinstance(v,types.MethodType)]
so you could call the methods directly without needing getattr
:
for method in methodList:
method()
You can call your dynamically obtained methods like this:
for method in methodList:
getattr(a, method)()
But the problem you will have is that this code will only work for methods that don't take any parameters.
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