It seems like the following python code which is a demo implementation of singleton design pattern working reverse order. can anyone explain why?
它看起来像下面的Python代码,它是单例设计模式逆序工作的演示实现。有谁能解释一下原因吗?
import random
class Rng:
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(Rng, cls).__new__(cls)
return cls._instance
def __init__(self, a, b):
self.number = random.randint(a, b)
b = Rng(4, 33)
a = Rng(100, 200)
print(a.number , b.number)
output: 148 148
enter image description here
在此处输入图像描述
since b is initiating first it should be always between 4 to 33, for a as well. But it's initiating a first
由于b是首先启动的,因此它应该始终在4到33之间,对于a也是如此。但它开启了第一个
更多回答
It's the same object, but you run __init__
twice. The second call overwrites the data from the first.
它是同一个对象,但您运行__init_两次。第二个调用将覆盖第一个调用中的数据。
In __new__
, you should add cls._instance.number = random.randint(*args, **kwargs)
, since you only want that to happen once, when the singelton is first created. There's no need to define __init__
at all.
在__new__中,您应该添加cls._instance.number=随机性.randint(*args,**kwargs),因为您只希望在第一次创建Singelton时发生一次。根本不需要定义__init__。
优秀答案推荐
我是一名优秀的程序员,十分优秀!