|
|
10鱼币
下面是我写的代码,但是为什么第一次运行时会报错,第二次运行就又得到我想要的结果了.
import random
class R():
__x = None
def __new__(cls):
if cls.__x == None:
cls.__x = super().__new__(cls)
else:
return cls.__x
def __init__(self):
self.rdom = ''
for i in range(4):
self.rdom += str(random.randint(0,9))
def show(self):
print(self.rdom)
这个代码目的时生成一个4位的随机数.运行结果如图...
第一次声明后,无法调用.rdom属性,但是在原程序的基础上,再声明一次后,程序正常运行.
想请教这是为什么,以及如何修改.
PS.额外的问一下关于上面 super().__new__(cls) 如何理解这句话,以及为何要传入cls参数.
__x = None
def __new__(cls):
if cls.__x == None:
_x你想做什么用
|
最佳答案
查看完整内容
__x = None
def __new__(cls):
if cls.__x == None:
_x你想做什么用
|