我正在学习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)
有可能做我正在尝试的事情吗?如果不是,还有另一种方法吗?
欢迎任何建议.
干杯.
Ale*_*lli 22
分配给参数或任何其他局部变量(barename)不可能在函数外部产生任何影响; 这适用于您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
Run Code Online (Sandbox Code Playgroud)
我在这里做了其他的改进,例如拔除了全局,旧式的等等.
更好的是使用Borg(又名monostate)而不是你选择的Highlander(又名单身人士),但这与你所询问的问题不同;-).
来自Design Pattern的Bruce Eckel的代码片段:我对它是如何工作感到困惑
class Borg:
_shared_state = {}
def __init__(self):
self.__dict__ = self._shared_state
class MySingleton(Borg):
def __init__(self, arg):
Borg.__init__(self)
self.val = arg
def __str__(self): return self.val
x = MySingleton('sausage')
print x
y = MySingleton('eggs')
print y
z = MySingleton('spam')
print z
print x
print y
print ´x´
print ´y´
print ´z´
output = '''
sausage
eggs
spam
spam
spam
<__main__. MySingleton instance at 0079EF2C>
<__main__. MySingleton instance at 0079E10C>
<__main__. MySingleton instance at 00798F9C>
'''
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13133 次 |
| 最近记录: |