| 
 | 
 
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册  
 
x
 
python3.3 以上版本的新式类中,如何在同时覆盖 __new__ 和 __init__ 时,将自定义的额外参数从 __new__ 传入 __init__ ?按我对new方法的理解不是可以处理一下传进来的参数吗,可为什么会出现图片中的问题,难道new方法只能处理不可改变类型的参数? 
>>> class CapStr(): 
        def __init__(self,n): 
                self.n=n 
        def __new__(cls,n): 
                n=10+n 
                return super().__new__(cls,n) 
 
         
>>> a=CapStr(10) 
Traceback (most recent call last): 
  File "<pyshell#60>", line 1, in <module> 
    a=CapStr(10) 
  File "<pyshell#59>", line 6, in __new__ 
    return super().__new__(cls,n) 
TypeError: object.__new__() takes exactly one argument (the type to instantiate) 
不会继承自float,而是继承自 numbers.Rational
 
__new__ 接收到的参数和 __init__ 接收到的是同一个对象。  
 
 
 |   
 
 
 
 |