Python通过魔术方法实现运算符重载,如__add__、__mul__等,使自定义类支持+、*等操作,需注意类型检查、行为一致性及可读性,适用于向量、矩阵等数学对象,提升代码简洁性与直观性。

Python 运算符重载,简单来说,就是让你自定义类的对象能够使用像
+
-
*
[]
解决方案:
Python 通过一些特殊方法(也称为魔术方法或双下划线方法)来实现运算符重载。比如,要重载加法运算符
+
__add__(self, other)
举个例子,假设你有一个
Vector
立即学习“Python免费学习笔记(深入)”;
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Vector({self.x}, {self.y})"
def __add__(self, other):
if isinstance(other, Vector):
return Vector(self.x + other.x, self.y + other.y)
else:
raise TypeError("Can only add Vector objects")
def __mul__(self, scalar):
if isinstance(scalar, (int, float)):
return Vector(self.x * scalar, self.y * scalar)
else:
raise TypeError("Can only multiply by a number")
# 使用示例
v1 = Vector(2, 3)
v2 = Vector(1, 4)
v3 = v1 + v2 # 调用 __add__
print(v3) # 输出: Vector(3, 7)
v4 = v1 * 5 # 调用 __mul__
print(v4) # 输出: Vector(10, 15)
#v5 = v1 + 5 # 会抛出TypeError,因为我们只定义了Vector + Vector这里,
__add__
Vector
__mul__
Vector
TypeError
运算符重载有哪些常见的魔术方法?
Python 提供了很多魔术方法来重载不同的运算符。一些常见的包括:
__add__(self, other)
__sub__(self, other)
__mul__(self, other)
__truediv__(self, other)
__floordiv__(self, other)
__mod__(self, other)
__pow__(self, other)
__eq__(self, other)
__ne__(self, other)
__lt__(self, other)
__gt__(self, other)
__le__(self, other)
__ge__(self, other)
__getitem__(self, key)
__setitem__(self, key, value)
__delitem__(self, key)
__len__(self)
__contains__(self, item)
注意,对于某些运算符,比如
+
__radd__
a + b
a
__add__
__add__
NotImplemented
b
__radd__
运算符重载的注意事项和最佳实践?
+
TypeError
+=
+
NotImplemented
NotImplemented
什么时候应该使用运算符重载?
运算符重载最适合用于创建自定义数据类型,这些类型在数学上或逻辑上与内置类型相似。例如,复数、向量、矩阵、集合等。 如果你只是想执行一些简单的操作,或者你的数据类型与内置类型没有明显的相似之处,那么使用普通的方法可能更合适。
运算符重载也常用于构建领域特定语言 (DSL),使代码更接近问题的自然语言。 但要小心,过度使用会使代码难以理解。
总而言之,运算符重载是一个强大的工具,但需要谨慎使用。 权衡简洁性、可读性和性能,并确保你的运算符重载的行为符合其通常的含义。
以上就是如何重载Python运算符?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号