Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a list of a class's methods and dynamically call the methods on the class

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()
like image 963
9monkeys Avatar asked Dec 27 '22 20:12

9monkeys


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

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()
like image 177
unutbu Avatar answered May 20 '23 10:05

unutbu


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.

like image 42
David Heffernan Avatar answered May 20 '23 12:05

David Heffernan