提问人:Emam Kownine 提问时间:9/10/2023 最后编辑:Emam Kownine 更新时间:9/10/2023 访问量:37
为什么这个 python 代码的工作顺序相反
why this python code working reverse order
问:
看起来像以下 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
由于 B 首先启动,因此对于 A 来说,它应该始终在 4 到 33 之间。但它正在启动一个
答: 暂无答案
评论
__init__
__new__
cls._instance.number = random.randint(*args, **kwargs)
__init__