在 Python 中,如何实现运算符重载(Operator Overloading)
                           
天天向上
发布: 2025-05-29 23:52:38

原创
685 人浏览过

在 Python 中,**运算符重载(Operator Overloading)**允许你为自定义类定义运算符的行为,比如 +-==< 等。它通过 特殊方法(魔术方法) 实现,如 __add__()__eq__() 等。


一、基本示例:重载 + 运算符

以一个自定义的二维向量类 Vector2D 为例:

class Vector2D:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    # 重载 + 运算符
    def __add__(self, other):
        return Vector2D(self.x + other.x, self.y + other.y)

    def __repr__(self):
        return f"Vector2D({self.x}, {self.y})"

# 测试
v1 = Vector2D(1, 2)
v2 = Vector2D(3, 4)
print(v1 + v2)  # 输出:Vector2D(4, 6)

二、常用运算符及其魔术方法对照表

运算符魔术方法描述
+__add__(self, other)加法
-__sub__减法
*__mul__乘法
/__truediv__除法(真除法)
//__floordiv__地板除
%__mod__取模
**__pow__幂运算
==__eq__等于
!=__ne__不等于
<__lt__小于
<=__le__小于等于
>__gt__大于
>=__ge__大于等于

三、进一步示例:重载 ==<

class Student:
    def __init__(self, name, score):
        self.name = name
        self.score = score

    def __eq__(self, other):
        return self.score == other.score

    def __lt__(self, other):
        return self.score < other.score

# 测试
s1 = Student("Alice", 90)
s2 = Student("Bob", 85)
print(s1 == s2)  # False
print(s1 < s2)   # False

四、注意事项

  1. 类型检查是个好习惯
   def __add__(self, other):
       if isinstance(other, Vector2D):
           return Vector2D(self.x + other.x, self.y + other.y)
       return NotImplemented
  1. 应始终实现成对的方法(如实现了 __eq__,最好也实现 __ne__
  2. 不可滥用重载:避免过度重载造成代码难以理解。

五、出站参考链接


六、总结

特性说明
灵活性高可为类自定义运算行为
使用魔术方法__add__, __eq__
用于自定义类适合 向量/矩阵/复数/模型对象
推荐搭配使用__str____repr__ 更易调试

更多详细内容请关注其他相关文章!

发表回复 0

Your email address will not be published. Required fields are marked *