小编Jon*_*San的帖子

Python单例/对象实例化

我正在学习Python,并且我一直在尝试将Singleton类型的类作为测试.我的代码如下:

_Singleton__instance = None

class Singleton:
    def __init__(self):
        global __instance
        if __instance == None:           
            self.name = "The one"
            __instance = self
        else:
            self = __instance
Run Code Online (Sandbox Code Playgroud)

这部分工作,但self = __instance部分似乎失败了.我已经包含了解释器的一些输出来演示(上面的代码保存在singleton.py中):

>>> import singleton
>>> x = singleton.Singleton()
>>> x.name
'The one'
>>> singleton._Singleton__instance.name
'The one'
>>> y = singleton.Singleton()
>>> y.name
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: Singleton instance has no attribute 'name'
>>> type(y)
<type 'instance'>
>>> dir(y)
['__doc__', '__init__', '__module__']
Run Code Online (Sandbox Code Playgroud)

有可能做我正在尝试的事情吗?如果不是,还有另一种方法吗?

欢迎任何建议.

干杯.

python singleton

6
推荐指数
2
解决办法
1万
查看次数

标签 统计

python ×1

singleton ×1