|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- class Nstr(int):
- def __init__(self, arg=''):
- if isinstance(arg, str):
- self.total = 0
- for each in arg:
- self.total += ord(each)
- else:
- print("参数错误!")
- def __add__(self, other):
- return self.total + other.total
复制代码
想计算两个字符串的AscII码和的加法,以上做法为啥会报错呢?
本帖最后由 Twilight6 于 2020-7-6 19:10 编辑
[b]
你的原本代码也没问题,是不是你自己实例化时候的问题?
你代码没有重写 __new__ 所以 __new__ 会自动将示例对象返回给 __init__
但是还是要记住,继承不可变类型的时候记得应该重写 __new__ 而不是 __init__哈:
这是你原来的代码,运行正常:
- class Nstr(int):
- def __init__(self, arg=''):
- if isinstance(arg, str):
- self.total = 0
- for each in arg:
- self.total += ord(each)
- else:
- print("参数错误!")
- def __add__(self, other):
- return self.total + other.total
- a = Nstr('1')
- b = Nstr('2')
- print(a+b)
复制代码
还有一个问题我重写了__add__(self,other)方法,那self.total + other.total时,加号不会调用__add__(self,other)方法,之后就一直无限递归吗?
__add__ 是对整个类而言的,不是对里面的实例属性而言的,你把 return 写成 self + other 就会无限递归,因为 self 和 other 就是类本身,所以 __add__ 会捕获 + 法运算导致无限递归
[/b]
|
|