列出类的方法并动态调用这些方法

5 投票
5 回答
3932 浏览
提问于 2025-04-16 18:02

有没有办法获取一个类的方法列表,然后在这个类的实例上调用这些方法呢?我见过一些代码可以列出一个类的方法,但还没找到可以在类的实例上调用这些方法的例子。

假设有一个类:

class Test:

def methodOne(self):
    print 'Executed method one'


def methodTwo(self):
    print 'Executed method two'

然后你列出了这个类的方法:

import inspect

a = Test()

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

我想在这个类的一个实例上调用methodList中的每一个方法,像这样:

for method in methodList:
     a.method()

结果将和下面的内容相同:

a.methodOne()
a.methodTwo()

5 个回答

2

你可以这样调用你动态获取到的方法:

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

但是你会遇到一个问题,那就是这段代码只适用于那些不需要任何参数的方法。

2

你为什么只保留方法的名字,而不保留方法本身呢?inspect.getmembers 返回的是可以直接调用的绑定方法:

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

使用 getattr(a, methodname) 可以根据方法的名字(字符串形式)来访问实际的方法,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()

这样可以得到

one
two

正如 Jochen Ritzel 指出的,如果你更关心实际的方法(可以调用的对象),而不是方法的名字(字符串),那么你应该把 methodList 的定义改成

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

这样你就可以直接调用这些方法,而不需要使用 getattr 了:

for method in methodList:
    method()

撰写回答