python中的“其他”是什么意思?

Cos*_*iju 3 python oop python-3.x

所以我刚开始在python 3 中学习面向对象的编程,我遇到了“ __add__”方法,我不明白“其他”是什么以及它做什么。我试图在互联网上寻找答案,但一无所获,这是我的代码示例:

import math

class MyClass:

    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __add__(self, other):
        f = self.x + other.x
        e = self.y + other.y
Run Code Online (Sandbox Code Playgroud)

Tho*_*mas 8

“其他”是什么以及它做什么。

它是参数的名称。该参数other是(例如)的另一个实例MyClass。以下面的例子为例:

a = MyClass(1, 2)
b = MyClass(3, 4)
# the next line calls MyClass.__add__ on the instance a
c = a + b 
Run Code Online (Sandbox Code Playgroud)

在这种情况下aselfbother

__add__您示例中的代码不完整,它应该真正返回一个新MyClass实例。

def __add__(self, other):
    f = self.x + other.x
    e = self.y + other.y
    return MyClass(f, e)
Run Code Online (Sandbox Code Playgroud)