|  | 
 
| 
本帖最后由 雷楼某 于 2020-9-2 11:10 编辑
x
马上注册,结交更多好友,享用更多功能^_^您需要 登录 才可以下载或查看,没有账号?立即注册  
 看到小甲鱼课程魔术方法,对__new__()进行了重写,但是自己写了两个类重写__new__()方法,就出错了。
 按理来说不应该打印出来传入的参数-1吗。
 
 >>> class num1:
 def __init__(self,x):
 print(self.x)
 
 
 >>> class num2(num1):
 def __new__(cls,x):
 x=x-1
 return num1.__new__(cls,x)
 
 
 >>> num = num2(10)
 Traceback (most recent call last):
 File "<pyshell#9>", line 1, in <module>
 num = num2(10)
 File "<pyshell#8>", line 4, in __new__
 return num1.__new__(cls,x)
 TypeError: object.__new__() takes exactly one argument (the type to instantiate)
 
 本帖最后由 sunrise085 于 2020-9-2 13:27 编辑 
有这么几个问题 
第一,你的 class num1,没有重载__new__方法,那么有个默认的__new__方法,该默认方法没有参数,但你在num2的__new__中调用num1 的__new__方法却给了参数x 
第二,你的num1中尚未定义self.x,就print(self.x)会报错,当然你的程序还没有执行到那里就出错了,所以没有报出这个错误
 
猜测你可能是想这样定义,num1需要是 int 的子类
 复制代码class num1(int):
    def __init__(self,x):
        self.x=x
        print(self.x)
    def __new__(cls,x):
        x=x-1
        return int.__new__(cls,x)
class num2(num1):
    def __new__(cls,x):
        x=x-1
        return num1.__new__(cls,x)
num2(10)
 | 
 |