1
クラスのIDをエンコードするファイルを保存しようとしています。ファイルを読み込んでクラスを呼び出し、データを保存するファイルに - > ファイルから読み込み、ファイル入力に基づいて新しいクラスをインスタンス化します。
id_class:(arguments)
読み込みファイルよりも、読み込みファイルが適切なクラスのリストから呼び出され、引数を渡すことになります。
このような何か:
class foo:
id = 1
def __init__(self):
self.attr = 10
def __str__(self):
return str(self.attr)
class bar:
id = 2
def __init__(self):
self.attr = 20
def __str__(self):
return str(self.attr)
def create_foo():
return foo
def create_bar():
return bar
class_dict = {1:create_foo(),2:create_bar()}
class_index = [1,2,1,2,1,1,1,2,2,2,1] #data read from file
class_list = [] #output list containing the newly instanciated bar or foo
for index in class_index:
c = class_dict[index]
class_list.append(c)
しかし、このコードは、例えば、fooのclass_listに追加し、私が変更した場合、属性がリスト全体に変更されますので、唯一のクラスです。例えば
:
10 20 10 20 10 10 10 20 20 20 10
-------------
15 20 15 20 15 15 15 20 20 20 15
と次のようになります:
for classe in class_list:
print classe,
print "\n-------------"
class_list[0].attr = 15
for classe in class_list:
print classe,
出力がある
10 20 10 20 10 10 10 20 20 20 10
-------------
15 20 10 20 10 10 10 20 20 20 10
pythonの魔法!それは動作します...しかし、なぜですか? – Pella86
そこに、私はちょうど変更を説明した:) –
ありがとう、私は自分自身に新しいオブジェクトをインスタンス化するように頼んでいた;) – Pella86