9mo*_*eys 4 python methods class
是否可以获取类的方法列表,然后在类的实例上调用方法?我遇到过编写类的方法列表的代码,但是我没有找到一个也调用类实例上的方法的例子.
鉴于课程:
class Test:
def methodOne(self):
print 'Executed method one'
def methodTwo(self):
print 'Executed method two'
Run Code Online (Sandbox Code Playgroud)
然后列出类的方法:
import inspect
a = Test()
methodList = [n for n, v in inspect.getmembers(a, inspect.ismethod)]
Run Code Online (Sandbox Code Playgroud)
我想methodList在类的实例上调用每个方法,例如:
for method in methodList:
a.method()
Run Code Online (Sandbox Code Playgroud)
结果相当于:
a.methodOne()
a.methodTwo()
Run Code Online (Sandbox Code Playgroud)
使用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()
Run Code Online (Sandbox Code Playgroud)
产量
one
two
Run Code Online (Sandbox Code Playgroud)
正如Jochen Ritzel指出的那样,如果你对实际方法(可调用对象)比方法名(字符串)更感兴趣,那么你应该改变定义methodList为
methodList = [v for n, v in inspect.getmembers(a, inspect.ismethod)
if isinstance(v,types.MethodType)]
Run Code Online (Sandbox Code Playgroud)
所以你可以直接调用方法而不需要getattr:
for method in methodList:
method()
Run Code Online (Sandbox Code Playgroud)
您可以像这样调用动态获取的方法:
for method in methodList:
getattr(a, method)()
Run Code Online (Sandbox Code Playgroud)
但您将遇到的问题是,此代码仅适用于不带任何参数的方法。