【发布时间】:2018-04-02 13:21:46
【问题描述】:
我正在尝试通过 dir() 提取类名,并通过 for 循环中的变量名动态创建它们的实例。如何让 python 将“项目”解释为变量名而不是“不存在的”类名。
>>> class cls1():
... def __init__(self):
... self.speak = 'say cls1'
... def replay(self):
... print self.speak
...
>>> for item in dir():
... if item[:2] != '__':
... print 'item = ', item
... x = item()
... x.reply()
...
item = cls1
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
TypeError: 'str' object is not callable
【问题讨论】: