gpt4 book ai didi

why this python code working reverse order(为什么这段python代码按相反的顺序运行)

转载 作者:bug小助手 更新时间:2023-10-25 18:32:59 27 4
gpt4 key购买 nike



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__。

优秀答案推荐
更多回答

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