如何(+, -, *, /, ... , //)
在 python 中的对象上重载运算符。
例子:
a = Vector(3, 5)
b = Vector(2, 7)
print(a + b) # Output: <Vector (5.000000, 12.000000)>
print(b - a) # Output: <Vector (-1.000000, 2.000000)>
print(b * 1.3) # Output: <Vector (2.600000, 9.100000)>
print(a // 17) # Output: <Vector (0.000000, 0.000000)>
print(a / 17) # Output: <Vector (0.176471, 0.294118)>
Vector
以下课程在哪里:
class Vector(object):
def __init__(self, x, y):
self.x = x
self.y = y
Python 中的一切都是对象。每个对象都有一些特殊的内部方法,用于与其他对象交互。通常,这些方法遵循命名约定
__action__
。统称为 Python 数据模型。您可以重载这些方法中的任何一个。这通常用于 Python 中的运算符重载。下面是一个使用 Python 数据模型的运算符重载示例。该类
Vector
创建两个变量的简单向量。我们将使用运算符重载为二向量数学运算添加适当的支持。运算符表
下面是可以在类中重载的运算符,以及所需的方法定义,以及在表达式中使用的运算符的示例。
参考: Medium - (Overloading) — Python 中的重载运算符