Reputation: 1784
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()
Upvotes: 5
Views: 4168
Reputation: 879749
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()
Upvotes: 9
Reputation: 107638
Why do you keep the name of the method and not the method itself? inspect.getmembers
returns bound method's which can be called directly:
for name, method in inspect.getmembers(a, inspect.ismethod):
print "Method", name, "returns", method()
Upvotes: 2
Reputation: 613013
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.
Upvotes: 2
Reputation: 13117
As David Heffernan pointed out, this will only work for methods that don't take any parameters.
for method in methodList:
getattr(a, method)()
Upvotes: 1
Reputation: 822
for method in methodList: eval ("a.%s()" % method)
For method without parameters except self.
Upvotes: -3