Python 中的运算符重载无法理解

问题描述 投票:0回答:1

我的代码

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):
      return f"{self.x}i+{self.y}j"``

    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)

p1=Point(1,2)
print(p1)
p2=Point(3,4)
print(p2)

print(p1+p2)
print(type(p1+p2))

结果

1i+2j
3i+4j
4i+6j
<class '__main__.Point'>

我无法理解这段代码是如何工作的。 请有人用简单的语言给我解释一下。

python python-3.x operator-overloading
1个回答
0
投票

高度简化。

当 python 看到 x + y 时,它会查看

x
是否是实现
__add__
的对象。如果失败,它会查看 y 是否是实现
__radd__
的对象。如果这两个都失败,它会进行正常操作。

在您的代码中,

x
有一个
__add__
方法,因此
x+y
被解释为
x.__add__(y)

© www.soinside.com 2019 - 2024. All rights reserved.