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

5 投票
2 回答
5306 浏览
提问于 2025-04-16 08:10

我想要用一组特定的参数来调用一个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 个回答

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

我不太明白你为什么想这么做。通常在像单元测试这样的场景中,你会先给你的类提供一些输入,然后在每个测试方法里引用这些输入。

使用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

撰写回答