|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
为什么在
class New_int(int):
def __add__(self,other):
return int.__sub__(self,other)
def __sub__(self,other):
return int.__add__(self,other)
__sub__(self,other)调用的方法不是这个类前面定义的 __add__(self,other)方法 而是int类的方法
在class Capstr(str):
def __new__(cla,string):
string=string.upper()
return str.__new__(cla,string)
中返回的方法是Capstr()的__new__(cla,string)方法 不是Str自身的方法,是因为Str没有__new__(cla,string)方法吗
__sub__(self,other)调用的方法不是这个类前面定义的 __add__(self,other)方法 而是int类的方法
因为你把 New_int 这个类的 __add__(self,other) 方法重写了,重写就把原来继承了 int 的 __add__(self,other) 方法给覆盖了 导致完全没有原本的 __add__(self,other) 功能, 所以要调用 父类 int 的__add__(self,other) 方法
中返回的方法是Capstr()的__new__(cla,string)方法 不是Str自身的方法,是因为Str没有__new__(cla,string)方法吗
class Capstr(str):
def __new__(cla,string):
string=string.upper()
return str.__new__(cla,string)
就是调用 str 类的 __new__方法呀,不是调用Capstr 的方法,而且在类中肯定会有 __new__ 方法,因为这个方法要将实例化对象传给 __init__ ,在实例化有着重要的意义和作用
你之前都没继承也没重写__new__方法 是因为Python 默认继承了 object 类的 __new__方法
|
|