【问题标题】:dynamically named singleton properties across instances in pythonpython中跨实例动态命名的单例属性
【发布时间】: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


    【解决方案1】:

    好的,我想出了自己的答案。通过使用 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]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-31
      • 1970-01-01
      • 2020-05-14
      • 2012-05-14
      • 1970-01-01
      相关资源
      最近更新 更多