开发者

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

开发者 https://www.devze.com 2023-03-07 19:40 出处:网络
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 exampl

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 cl开发者_如何学编程ass'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.


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


As David Heffernan pointed out, this will only work for methods that don't take any parameters.

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


for method in methodList: eval ("a.%s()" % method)

For method without parameters except self.

0

精彩评论

暂无评论...
验证码 换一张
取 消