首页 > 解决方案 > 在python中定义单例类的麻烦

问题描述

我正在尝试使用基类在 python 中定义 Singleton 类,遵循此链接的方法 2 ,这是我的代码

class SingletonBase(object):

     def __new__(cls, slots=None):
        print(cls)
        if not hasattr(cls, 'instance'):
            print(object.__new__(cls))
            cls.instance = object.__new__(cls, slots=None)
            cls.instance.init_instance(slots=None)
        #else:
        return cls.instance


class Foo(SingletonBase):

    def init_instance(self, slots=None):
        self.slots = slots
        print(slots)

    def __init__(self):
        print('execute init.')

,当我在我的 python 终端上运行时

Foo()

我收到这个错误

AttributeError: type object 'Foo' has no attribute 'instance'

请帮助,如何解决这个问题。我尝试instance = None在 SingletonBase 和 Foo 类级别进行定义,但没有解决。

标签: singleton

解决方案


推荐阅读