【发布时间】:2015-09-09 05:04:44
【问题描述】:
我正在学习 Python,我一直在尝试实现一个单例类作为测试。我的代码如下:
_Singleton__instance = None
class Singleton:
def __init__(self):
global __instance
if __instance == None:
self.name = "The one"
__instance = self
else:
self = __instance
这部分有效,但 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__']
有可能做我正在尝试的事情吗?如果没有,还有其他方法吗?
欢迎提出任何建议。
干杯。
【问题讨论】:
-
除了一个有趣的学习练习,你有这个 Singleton 的用例吗?有时单例可能比这简单得多。 Singleton 设计模式——在一定程度上——是一种 Smalltalk/C++/Java 主义,在 Python 中并不经常需要。