python运算符重载__radd__和__add__ [英] python operator overloading __radd__ and __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会查看x
和y
的类型,以确定是调用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.val
和other
的类型,以确定是调用self.val.__add__
还是other.__radd__
.由于它们是不相关的类型int
和Commuter1
,因此它将首先尝试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会查看other
和self.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屋!