作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在学习 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__']
是否可以做我正在尝试的事情?如果没有,还有其他方法吗?
欢迎提出任何建议。
干杯。
最佳答案
分配给参数或任何其他局部变量(裸名)永远不可能在函数外产生任何影响;这适用于您的 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 (又名单态)而不是您选择的 Highlander(又名单例),但这与您询问的问题不同;-)。
关于Python单例/对象实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1363839/
我最近购买了《C 编程语言》并尝试了 Ex 1-8这是代码 #include #include #include /* * */ int main() { int nl,nt,nb;
早上好!我有一个变量“var”,可能为 0。我检查该变量是否为空,如果不是,我将该变量保存在 php session 中,然后调用另一个页面。在这个新页面中,我检查我创建的 session 是否为空,
我正在努力完成 Learn Python the Hard Way ex.25,但我无法理解某些事情。这是脚本: def break_words(stuff): """this functio
我是一名优秀的程序员,十分优秀!