2012-03-25 148 views
0

我已代码就像如下:

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()函数,任何人都可以有任何想法实现的功能?

+5

为什么不直接使用数组? – 2012-03-25 14:26:29

+2

为什么有人会使用最无用的编程语言功能之一? – Griwes 2012-03-25 14:29:59

+0

PHP *中的'$$'功能真的很糟糕。我不会推荐任何人使用它。 – 2012-03-25 14:36:51

回答

7

使用listdict来存储您的变量。例如:

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() 
+1

Minor nitpick:抛出TypeError:doSomething()不带任何参数(给出1)'。 – bernie 2012-03-25 14:41:56

+0

啊,当然*拍头*。谢谢。 – 2012-03-25 14:42:43

+0

非常感谢。我从中学到了很多东西。 – Searene 2012-03-26 06:09:41

相关问题