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

新手上路,请多包涵

所以我刚开始学习 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

原文由 Costel biju 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 449
1 个回答

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

它是参数的名称。参数 other 是(例如) MyClass 的另一个实例。举个例子:

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

在这种情况下 aselfbother

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

 def __add__(self, other):
    f = self.x + other.x
    e = self.y + other.y
    return MyClass(f, e)

原文由 Thomas 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题