python运算符重载__radd__和__add__ [英] python operator overloading __radd__ and __add__

查看:252
本文介绍了python运算符重载__radd__和__add__的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习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)

我得到了以下结果

单独使用时,我了解__radd____add__的工作方式.但是对于x + y行,我不确定为什么同时调用__radd____add__方法.

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.

推荐答案

首先,Python会查看xy的类型,以确定是调用x.__add__还是y.__radd__.由于它们都是相同的Commuter1类型,因此它将首先尝试x.__add__.

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.

然后,在您的__add__方法中,执行以下操作:

Then, inside your __add__ method, you do this:

return self.val + other

因此,Python会查看self.valother的类型,以确定是调用self.val.__add__还是other.__radd__.由于它们是不相关的类型intCommuter1,因此它将首先尝试int.__add__.

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.

但是int.__add__对于未知类型返回NotImplemented,因此Python回退到调用other.__radd__.

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

在您的__radd__方法中,您可以执行以下操作:

Inside your __radd__ method, you do this:

return other + self.val

因此,Python会查看otherself.val的类型,以确定是调用other.__add__还是self.val.__radd__.由于它们都是相同的int类型,因此它将首先尝试__add__.

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.

当然int.__add__可在另一个int上使用,因此它返回__radd__内部的内部+的值,然后返回该值,该值又返回__add__内部的+的值,您将返回该值,并返回您打印的顶级+的值.

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.

这篇关于python运算符重载__radd__和__add__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆