我正在学习Python,我一直在尝试实现一个单例类型的类作为测试。我的代码如下:_Singleton__instance = None
class Singleton:
def __init__(self):
global __instance
if __instance == None:
self.name = "The one"
__instance = self
else:
self = __instance
这在一定程度上起作用,但self=\u实例部分似乎失败了。我已经包含了一些解释程序的输出来演示(上面的代码保存在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 "", line 1, in
AttributeError: Singleton instance has no attribute 'name'
>>> type(y)
>>> dir(y)
['__doc__', '__init__', '__module__']
有可能做我想做的事吗?如果没有,还有别的办法吗?
欢迎提出任何建议。
干杯。