我到Python新手,我想类似的问题已经被问(包括本: ?你可以使用一个字符串在Python中实例类 ),但我不明白的答案或如何应用它们。
我试图创建使用的是什么,我会在列表中所称的“实例名称”一类的多个实例。
这里是什么,我试图做一个例子:
class InstanceNames():
def __init__(self):
self.names = ['inst1', 'inst2', 'inst3']
class DoSomething():
instances = []
def __init__(self):
DoSomething.instances.append(self)
instance_names = InstanceNames()
for x in range(len(instance_names.names)):
print x
# following line not working at creating instances of DoSomething
instance_names.names[x] = DoSomething()
print DoSomething.instances
我改变了列表循环,现在我得到以下的输出:
0
1
2
[<__main__.DoSomething instance at 0x10cedc3f8>, <__main__.DoSomething instance at 0x10cedc440>, <__main__.DoSomething instance at 0x10cedc488>]
有用吗? 我很困惑我不知道。
好。 这是一些丑陋的代码,但这里是我现在有:
class InstanceNames():
def __init__(self):
self.i_names = {'inst1': None, 'inst2': None, 'inst3': None}
self.o_names = ['foo', 'bar', 'baz']
class DoSomething():
instances = []
def __init__(self, blah_blah):
DoSomething.instances.append(self)
self.name = blah_blah
def testy(self, a):
a = a * 2
instance_names = InstanceNames()
for x in range(len(instance_names.i_names)):
print x
instance_names.i_names[x] = DoSomething(instance_names.o_names[x])
print "\n"
print DoSomething.instances
print "\n"
for y in DoSomething.instances:
print y.name
print y.testy(4)
print "\n"
这里是我的输出:
0
1
2
[<__main__.DoSomething instance at 0x10dc6c560>, <__main__.DoSomething instance at 0x10dc6c5a8>, <__main__.DoSomething instance at 0x10dc6c5f0>]
foo
None
bar
None
baz
None
为什么是“名”可变印刷,但“暴躁”的方法是不是?