python类的实例化赋值给其他对象_Python单例/对象实例化

我正在学习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 "", line 1, in

AttributeError: Singleton instance has no attribute 'name'

>>> type(y)

>>> dir(y)

['__doc__', '__init__', '__module__']

有可能做我想做的事吗?如果没有,还有别的办法吗?

欢迎提出任何建议。

干杯。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值