Python 我可以在PHP中使用$$var这样的变量吗?
我有如下代码:Python 我可以在PHP中使用$$var这样的变量吗?,python,Python,我有如下代码: 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_s
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()
当然它不起作用,因为string没有do_something()函数,任何人都能想到实现这个函数吗?使用
列表或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()
为什么不直接使用数组呢?为什么会有人使用最无用的编程语言功能之一呢?PHP中的$
功能真是难看透了。我不推荐任何人使用它。@Griwes:我不懂Python(我在问题标题中看到了PHP,最初认为这是一个PHP问题),所以不确定你的评论是针对我还是针对OP;Python中的数组有什么问题?@OliCharlesworth,我说的是使用testX
而不是test[X]
,当然了。小毛病:抛出TypeError:doSomething()不带参数(给定1个)
。