【发布时间】:2017-10-12 23:59:31
【问题描述】:
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 函数中,我有这一行:
Factory.__setattr__(Factory, new_attribute, new_instance)
文档说 setattr 想要一个实例作为第一个参数,但我希望能够跨实例设置动态命名的属性。这样下次我调用 get_singleton 函数时,它将返回我在之前调用中创建的相同类实例。我希望能够跨实例创建动态命名的单例属性。
这是我从外部调用此函数的方式:
manager = Factory().get_singleton('Manager')
有没有办法在 python 中做到这一点?
谢谢
【问题讨论】:
标签: python oop dynamic factory