我的代码如下:
class test:
def do_something():
pass
test1 = test()
test2 = test()
test3 = test()
test4 = test()
test5 = test()
test6 = test()
test7 = test()
test8 = test()
test9 = test()
...
现在我需要调用每个实例的函数,就像那样:
test1.do_something()
test2.do_something()
test3.do_something()
test4.do_something()
test5.do_something()
test6.do_something()
test7.do_something()
test8.do_something()
test9.do_something()
...
太多的类,所以我认为可能是for循环可以完成工作:
for i in range(1, 30):
("test" + str(i)).do_something()
当然它不起作用,因为字符串没有do_something()函数,任何人都可以有任何想法实现这个功能吗?
答案 0 :(得分:7)
使用list
或dict
存储您的变量。例如:
class Test:
def doSomething(self):
pass
tests = [Test() for i in range(9)]
# Now to invoke the functions:
tests[0].doSomething()
tests[1].doSomething()
...
tests[8].doSomething()
# or if you want to do them all at once:
for item in tests:
item.doSomething()