我正在学习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 "<stdin>", line 1, in <module>
AttributeError: Singleton instance has no attribute 'name'
>>> type(y)
<type 'instance'>
>>> dir(y)
['__doc__', '__init__', '__module__']
有可能做我想做的事吗?如果没有,还有别的办法吗?
欢迎提出任何建议。
干杯。
赋值给参数或任何其他局部变量(barename)可能永远不会在函数之外产生任何影响;这适用于您的
self = whatever
,就像它适用于任何其他赋值给(barename)参数或其他局部变量一样。相反,重写
__new__
:我在这里做了其他的增强,比如去掉global、旧样式类等
更好的方法是使用Borg(又名monostate)而不是您选择的Highlander(又名singleton),但这与您询问的问题不同;-。
来自Singleton Pattern (Python):
Bruce Eckel's code snippet from Design Pattern: I'm confused on how it works
相关问题 更多 >
编程相关推荐