Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在for循环中创建实例_Python_Instance - Fatal编程技术网

Python 在for循环中创建实例

Python 在for循环中创建实例,python,instance,Python,Instance,我试图通过dir()提取类名,并通过for循环中的变量名动态创建它们的实例。如何让python将“item”解释为变量名而不是“不存在”的类名 >>> class cls1(): ... def __init__(self): ... self.speak = 'say cls1' ... def replay(self): ... print self.speak ... >>> for item in dir

我试图通过dir()提取类名,并通过for循环中的变量名动态创建它们的实例。如何让python将“item”解释为变量名而不是“不存在”的类名

>>> 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
>>类cls1():
...     定义初始化(自):
...         self.speak='say cls1'
...     def重播(自我):
...         打印自述
...
>>>对于目录()中的项:
...     如果项目[:2]!='\uuuuu':
...         打印“项目=”,项目
...         x=项目()
...         x、 答复()
...
项目=cls1
回溯(最近一次呼叫最后一次):
文件“”,第4行,在
TypeError:“str”对象不可调用
dir()
生成已排序的名称列表;这些只是线。它们不是对实际对象的引用。不能对字符串应用调用

而是使用,这将为您提供名称和实际对象的映射:

for name, obj in globals().items():
    if not name.startswith('__'):
        print "name =", name
        instance = obj()
        instance.replay()

dir()
在模块级,没有参数,基本上返回
sorted(globals())

我想再问你一个问题……Python中没有办法将字符串计算为类名吗。也许通过评估??换句话说,我认为这个字符串可以与类名匹配,然后自动转换为引用。Thanks@Kris:
eval
只能作为最后手段使用。
globals()
字典提供了从字符串值到对象的直接映射。如果变量
name
中只有一个字符串名,那么
globals()[name]
将为您提供对象。谢谢。只是想澄清一下——你的例子在上面起了作用,一切都很好。我只是想知道做这件事的替代方法(而且不是最理想的)。再次感谢。