【Python】Python中重载运算符实现类对象的加减乘除

我们有时候需要对自己的类对象使用运算符进行操作,希望能够像C++那样实现运算符重载,那么就可以重载一下Python的一些方法来实现。

加法为例,Python中只需要在类对象中重载一下__add__(self, other)方法即可:

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

    def __str__(self):
        return "(" + str(self.x) + ", " + str(self.y) + ")"

    def __add__(self, other):
        self.x += other.x
        self.y += other.y
        return self


point1 = Point(1, 2)
point2 = Point(2, 4)
print(point1 + point2)
print(point1)
print(point2)

注意,在__add__(self, other)这里我的返回值是return self,这也就意味着,我是改变了加法前面的那个类对象的值。
在这里插入图片描述
可以看到,point1的值变了,而point2的值没变。

如果想要实现的效果是加法结束以后,加法两侧的值都不改变,则可以将__add__(self, other)方法的返回值改成:

def __add__(self, other):
    return Point(self.x + other.x, self.y + other.y)

在这里插入图片描述
同样的还有其他重载运算符的方法:

def __add__(self, other):
def __sub__(self, other):
def __mul__(self, other):
def __matmul__(self, other):
def __truediv__(self, other):
def __floordiv__(self, other):
def __mod__(self, other):
def __divmod__(self, other):
def __pow__(self, power, modulo=None):
def __lshift__(self, other):
def __rshift__(self, other):
def __and__(self, other):
def __or__(self, other):
def __xor__(self, other):
def __radd__(self, other):
def __rsub__(self, other):
def __rmul__(self, other):
  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
可以通过定义一个向量类来实现向量的加减乘除操作。以下是示例代码: ```python import numpy as np class Vector: def __init__(self, data): self.data = np.array(data) def __add__(self, other): if isinstance(other, Vector): return Vector(self.data + other.data) else: raise TypeError("Unsupported operand type for +") def __sub__(self, other): if isinstance(other, Vector): return Vector(self.data - other.data) else: raise TypeError("Unsupported operand type for -") def __mul__(self, other): if isinstance(other, (int, float)): return Vector(self.data * other) elif isinstance(other, Vector): return np.dot(self.data, other.data) else: raise TypeError("Unsupported operand type for *") def __truediv__(self, other): if isinstance(other, (int, float)): return Vector(self.data / other) else: raise TypeError("Unsupported operand type for /") def __repr__(self): return f"Vector({self.data})" ``` 在这个向量类,定义了向量加减乘除的运算符重载方法。可以使用 Vector([1, 2, 3]) 来创建一个向量对象,然后调用向量的加减乘除方法来进行相应的操作。示例代码如下: ```python # 定义两个向量 a = Vector([1, 2, 3]) b = Vector([4, 5, 6]) # 向量加法 c = a + b print("向量加法结果:", c) # 向量减法 d = a - b print("向量减法结果:", d) # 向量数乘 k = 2 e = k * a print("向量数乘结果:", e) # 向量点乘 f = a * b print("向量点乘结果:", f) ``` 输出结果为: ``` 向量加法结果: Vector([5 7 9]) 向量减法结果: Vector([-3 -3 -3]) 向量数乘结果: Vector([2 4 6]) 向量点乘结果: 32 ``` 需要注意的是,在进行向量加减法时,要确保两个向量的维度相同;在进行向量点乘时,要确保两个向量的长度相同。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

花无凋零之时

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值