在 for 循环中调用函数/类方法



我正在研究一些类,对于测试过程,能够在 for 循环中运行类方法将非常有用。我正在添加方法并更改它们的名称,我希望它在我运行类进行测试的文件中自动更改。

我使用下面的函数来获取我需要自动运行的方法列表(我为示例删除了一些其他条件语句,以确保我只运行某些需要测试并且只有 self 作为参数的方法(

def get_class_methods(class_to_get_methods_from):
import inspect
methods = []
for name, type in (inspect.getmembers(class_to_get_methods_from)):
if 'method' in str(type) and str(name).startswith('_') == False:
methods.append(name)
return methods

是否可以使用返回的列表"方法"在 for 循环中运行类方法?

或者有没有其他方法可以确保我可以在我的 testingrun 文件中运行我的类方法,而无需更改或添加我在类中更改的内容?

谢谢!

看起来你想要getattr(object, name[, default])

class Foo(object):
def bar(self):
print("bar({})".format(self))

f = Foo()
method = getattr(f, "bar")
method()

作为旁注:我不确定动态生成要测试的方法列表是一个好主意(对我来说看起来很像一个反模式( - 现在很难在没有整个项目的上下文的情况下分辨,所以请以所需的盐粒;)

最新更新