Python 中的重载运算符
pythonserver side programmingprogramming更新于 2025/4/25 11:56:17
假设您创建了一个 Vector 类来表示二维向量,当您使用加号运算符将它们相加时会发生什么?Python 很可能会对您大喊大叫。
但是,您可以在类中定义 __add__ 方法来执行向量加法,然后加号运算符将按照预期运行 −
示例
#!/usr/bin/python class Vector: def __init__(self, a, b): self.a = a self.b = b def __str__(self): return 'Vector (%d, %d)' % (self.a, self.b) def __add__(self,other): return Vector(self.a + other.a, self.b + other.b) v1 = Vector(2,10) v2 = Vector(5,-2) print v1 + v2
输出
执行上述代码时,会产生以下结果 −
Vector(7,8)
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

