Make a list of class methods and dynamically call class methods

Is it possible to get a list of class methods and then call methods in an instance of the class? I came across code that makes up a list of class methods, but I did not find an example that also calls methods in 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 will create a list of class methods:

 import inspect a = Test() methodList = [n for n, v in inspect.getmembers(a, inspect.ismethod)] 

I would like to call each method in methodList in an instance of the class, for example:

 for method in methodList: a.method() 

The result will be equivalent to:

 a.methodOne() a.methodTwo() 
+4
source share
5 answers

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() 

gives

 one two 

As Jochen Ritzel points out, if you are more interested in actual methods (called objects) than method names (strings), then you should change the definition from methodList to

 methodList = [v for n, v in inspect.getmembers(a, inspect.ismethod) if isinstance(v,types.MethodType)] 

so that you can directly call methods without requiring getattr :

 for method in methodList: method() 
+8
source

You can call your dynamically obtained methods as follows:

 for method in methodList: getattr(a, method)() 

But the problem is that this code will only work for methods that take no parameters.

+2
source

Why do you save the name of the method, not the method itself? inspect.getmembers returns a related method that can be called directly:

 for name, method in inspect.getmembers(a, inspect.ismethod): print "Method", name, "returns", method() 
+2
source

As David Heffernan noted, this will only work for methods that take no parameters.

 for method in methodList: getattr(a, method)() 
+1
source
 for method in methodList: eval ("a.%s()" % method) 

For a method without parameters other than self.

-3
source

All Articles