|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 非凡 于 2021-6-11 00:24 编辑
- class New_int(int):
- def __add__(self, other):
- return int.__add__(self,other) *2
- >>>a = New_int('11')
- >>>a + 1
- 24
- >>>a + 11
- 44
- >>>a + 0
- 22
复制代码
不解为什么做的上述加法。
视乎把a加的那个整数,像是作为了New_int()参数后返回了一个*2的整数。
不应该是a+1 ,返回的值为,23 (22+1)
a+11 返回值 11*2+11
- >>> b = 1
- >>> a + b
- 24
- >>> b + a
- 12
复制代码
同样疑惑,为什么 a + b返回值是24,不是 23,b不是赋值为1 吗、?
我最后的意思是用括号表示优先级,你带入代码干嘛...呃呃呃
你重写的 __add__ 是先执行 int.__add__ ,而 参数中 self 是指加号左边的对象,other 是指加号右边的对象
那么你执行 int.__add__(self,other) 是会将 __add__(self, other) 的 self 和 other 带入到 int.__add__(self,other) 中
那么你先不看 最后的 *2 肯定需要先执行完 int.__add__(self,other),即 int.__add__(a, 1) 计算结果为 12 后计算 *2 = 24
|
|