Python:使用给定的参数集调用对象的所有方法

sam*_*sam 5 python design-patterns

我想用一组给定的参数调用python对象实例的所有方法,即对于像这样的对象

class Test():
    def a(input):
        print "a: " + input
    def b(input):
        print "b: " + input
    def c(input):
        print "c: " + input
Run Code Online (Sandbox Code Playgroud)

我想写一个允许我运行的动态方法

myMethod('test')
Run Code Online (Sandbox Code Playgroud)

导致

a: test
b: test
c: test
Run Code Online (Sandbox Code Playgroud)

通过遍历所有test() - 方法.在此先感谢您的帮助!

kev*_*pie 11

不完全确定你为什么要这样做.通常在单元测试中,您可以在类上提供输入,然后在每个测试方法中引用它.

使用检查和目录.

from inspect import ismethod

def call_all(obj, *args, **kwargs):
    for name in dir(obj):
        attribute = getattr(obj, name)
        if ismethod(attribute):
            attribute(*args, **kwargs)

class Test():
    def a(self, input):
        print "a: " + input
    def b(self, input):
        print "b: " + input
    def c(self, input):
        print "c: " + input

call_all(Test(), 'my input')
Run Code Online (Sandbox Code Playgroud)

输出:

a: my input
b: my input
c: my input
Run Code Online (Sandbox Code Playgroud)