重载运算符在 Python 中如何工作?
pythonserver side programmingprogramming
我们知道,我们可以使用 + 运算符来添加数字,同时连接字符串。这是可能的,因为 + 运算符被 int 类和 str 类重载。运算符基本上是各自类中定义的方法。为运算符定义方法称为运算符重载。例如,要将 + 运算符与自定义对象一起使用,我们需要定义一个名为 __add__ 的方法。
示例
以下代码可以轻松理解运算符重载的工作原理
import math class Circle: def __init__(self, radius): self.__radius = radius def setRadius(self, radius): self.__radius = radius def getRadius(self): return self.__radius def area(self): return math.pi * self.__radius ** 2 def __add__(self, another_circle): return Circle( self.__radius + another_circle.__radius ) c1 = Circle(3) print(c1.getRadius()) c2 = Circle(6) print(c2.getRadius()) c3 = c1 + c2 # 这是因为我们通过添加方法 __add__ 重载了 + 运算符 print(c3.getRadius())
输出
这给出了输出
3 6 9
修改运算符的行为以使其与用户定义类型一起使用称为运算符重载。对于 Python 中的每个运算符,都有一个对应的特殊方法,例如 __add__。有关更多详细信息,请参阅 docs.python.org/ref/specialnames.html。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

