2017-10-12 89 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

SETATTR想要一個實例
Factory.__setattr__(Factory, new_attribute, new_instance) 

文檔說對於第一個參數,但我希望能夠跨實例設置動態命名的屬性。這樣下一次我調用get_singleton函數時,它將返回我在以前的調用中創建的同一個類實例。我希望能夠跨實例動態命名單例屬性。

這是我如何調用該函數來自外部:

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

有沒有辦法在Python做到這一點?

謝謝

回答

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]