我正在学习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__']
可以做我正在尝试的事情吗?如果没有,还有其他方法可以做到这一点吗?
欢迎任何建议。
Cheers.
分配给参数或任何其他局部变量(裸名)永远不可能在函数外部产生任何影响;这适用于你的self = whatever
就像对(裸名)参数或其他局部变量的任何其他赋值一样。
相反,覆盖__new__
:
class Singleton(object):
__instance = None
def __new__(cls):
if cls.__instance == None:
cls.__instance = object.__new__(cls)
cls.__instance.name = "The one"
return cls.__instance
我在这里做了其他增强,例如根除全局、旧式类等。
更好的是使用Borg http://www.aleax.it/5ep.html(又名单态)而不是您选择的高地人(又名单例),但这与您所问的问题不同;-)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)