Python中的特殊方法有哪些?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

模拟数值类型
可以通过在自定义对象中实现 __add__ 和 __mul__ 等特殊方法 ,令其支持 +、* 等运算符。
如下面的模拟向量的 Vector 类:
# vector.py
from math import hypot
class Vector:
  def __init__(self, x=0, y=0):
    self.x = x
    self.y = y
  def __repr__(self):
    return f'Vector({self.x}, {self.y})'
  def __abs__(self):
    return hypot(self.x, self.y)
  def __bool__(self):
    return bool(self.x or self.y)
  def __add__(self, other):
    return Vector(self.x + other.x, self.y + other.y)
  def __mul__(self, scalar):
    return Vector(self.x * scalar, self.y * scalar)