2011-10-24 10 views
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 

答えて

1

私は両方create方法を変更する - 彼らは括弧を欠落していた、彼らなしなしオブジェクトの新しいインスタンスが作成されました。また、class_dictcreateメソッドを呼び出さないように変更しました。代わりにclass_dictにアクセスした瞬間にインスタンス化を延期します:class_dict[index]()。変更されたコードは次のようになります。

class foo: 
    id = 1 
    def __init__(self): 
     self.attr = 10 

class bar: 
    id = 2 
    def __init__(self): 
     self.attr = 20 

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) 

for classe in class_list: 
    print str(classe.attr), 

print "\n-------------" 
class_list[0].attr = 15 

for classe in class_list: 
    print str(classe.attr), 
+0

pythonの魔法!それは動作します...しかし、なぜですか? – Pella86

+0

そこに、私はちょうど変更を説明した:) –

+0

ありがとう、私は自分自身に新しいオブジェクトをインスタンス化するように頼んでいた;) – Pella86

関連する問題