gpt4 book ai didi

Python单例/对象实例化

转载 作者:太空狗 更新时间:2023-10-29 22:00:21 24 4
gpt4 key购买 nike

我正在学习 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com