私は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
リストのforループを変更したところ、次の出力が得られました。
0
1
2
[<__main__.DoSomething instance at 0x10cedc3f8>, <__main__.DoSomething instance at 0x10cedc440>, <__main__.DoSomething instance at 0x10cedc488>]
それは機能しましたか?よくわからないので混乱しています。
Ok。これはいくつかの醜いコードですが、これが私が今持っているものです:
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
「name」バリアブル印刷が「testy」メソッドではないのはなぜですか?