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

时间:2010-12-07 08:14:48

标签: python design-patterns

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

这样的对象
class Test():
    def a(input):
        print "a: " + input
    def b(input):
        print "b: " + input
    def c(input):
        print "c: " + input

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

myMethod('test')

导致

a: test
b: test
c: test

迭代所有test() - 方法。在此先感谢您的帮助!

2 个答案:

答案 0 :(得分:11)

不确定为什么要这样做。通常在单元测试之类的东西中,你会在你的课上提供一个输入,然后在每个测试方法中引用它。

使用inspect和dir。

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

输出:

a: my input
b: my input
c: my input

答案 1 :(得分:1)

你真的不想这样做。 Python附带两个非常好的测试框架:请参阅文档中的unittestdoctest模块。

但你可以尝试类似的东西:

def call_everything_in(an_object, *args, **kwargs):
    for item in an_object.__dict__:
        to_call = getattr(an_object, item)
        if callable(to_call): to_call(*args, **kwargs)