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做到這一點?
謝謝