python加法运算符重载,python运算符重载__radd__和__add__

I'm currently learning python operator overloading (__radd__ and __add__ to be exact) and I have the following code

class Commuter1:

def __init__(self, val):

self.val = val

def __add__(self, other):

print('add', self.val, other)

return self.val + other

def __radd__(self, other):

print('radd', self.val, other)

return other + self.val

x = Commuter1(88)

y = Commuter1(99)

print(x + y)

I have got the following result

eb91aff0903422ff6f048bd9b5822a89.png

When used separately, I understand how __radd__ and __add__ works. But for the line x + y, I'm not sure why both __radd__ and __add__ methods are evoked.

解决方案

First, Python looks at the types of x and y to decide whether to call x.__add__ or y.__radd__. Since they're both the same type Commuter1, it tries x.__add__ first.

Then, inside your __add__ method, you do this:

return self.val + other

So, Python looks at the types of self.val and other to decide whether to call self.val.__add__ or other.__radd__. Since they're unrelated types int and Commuter1, it tries int.__add__ first.

But int.__add__ returns NotImplemented for a type it doesn't know about, so Python falls back to calling other.__radd__.

Inside your __radd__ method, you do this:

return other + self.val

So, Python looks at the types of other and self.val to decide whether to call other.__add__ or self.val.__radd__. Since they both the same type int, it tries __add__ first.

And of course int.__add__ works on another int, so it returns a value for the inner + inside your __radd__, which you return, which returns a value for the + inside __add__, which you return, which returns a value for the top-level +, which you print.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值