2017-10-12 4 views
2
class Factory: 
    def get_singleton(self, class_name): 
     if class_name not in Factory.__dict__: 
      new_instance = self.get_new_instance(class_name) 
      new_attribute = self.get_attribute_name_from_class_name(class_name) 
      Factory.__setattr__(Factory, new_attribute, new_instance) 
      return Factory.__getattribute__(new_attribute) 

の名前:は動的に私は、オブジェクトファクトリクラスを作っていますし、上記の私のget_singleton機能では、私はこのラインを持っているのpythonでのインスタンス間でのシングルトンのプロパティ

Factory.__setattr__(Factory, new_attribute, new_instance) 

ドキュメントはSETATTRインスタンスを望んでいると言います最初のパラメータについては、私はインスタンス間で動的に名前付きプロパティを設定できるようにしたいと思います。次回get_singleton関数を呼び出すと、以前の呼び出しで作成した同じクラスインスタンスが返されます。私はインスタンス間でダイナミックに名前のついたシングルトンプロパティを作ることができるようにしたい。 pythonでこれを行う方法は

manager = Factory().get_singleton('Manager') 

あり:ここで

は私が外からこの関数を呼び出す方法ですか?

ありがとう、

答えて

0

私は自分の答えを見つけました。 settattrを使うことで、私はインスタンス以外の属性を動的に作成することができます。ここにコードがあります。

class Factory: 
    @staticmethod 
    def get_singleton(class_name): 
     new_attribute = Factory.get_attribute_name_from_class_name(class_name) 
     if new_attribute not in Factory.__dict__: 
      new_instance = Factory.get_new_instance(class_name) 
      setattr(Factory, new_attribute, new_instance) 
     return Factory.__dict__[new_attribute] 
関連する問題