重载加法、减法和乘法运算符 [英] Overloading Addition, Subtraction, and Multiplication Operators

查看:40
本文介绍了重载加法、减法和乘法运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何重载加法、减法和乘法运算符,以便我们可以对两个大小不同或相同的向量进行加、减和乘?例如,如果向量的大小不同,我们必须能够根据最小的向量大小对两个向量进行加、减或乘?

How do you go about overloading the addition, subtraction, and multiplication operator so we can add, subtract, and multiply two vectors of different or identical sizes? For example, if the vectors are different sizes we must be able to add, subtract, or multiply the two vectors according to the smallest vector size?

我已经创建了一个函数,允许您修改不同的向量,但现在我正在努力重载运算符并且不知道从哪里开始.我将粘贴下面的代码.有任何想法吗?

I've created a function that allows you to modify different vectors, but now I'm struggling to overload the operators and haven't a clue on where to begin. I will paste the code below. Any ideas?

def __add__(self, y):
    self.vector = []
    for j in range(len(self.vector)):
        self.vector.append(self.vector[j] + y.self.vector[j])
    return Vec[self.vector]

推荐答案

为类定义__add____sub____mul__ 方法,就是这样.每个方法接受两个对象(+/-/*的操作数)作为参数,并期望返回计算结果.

You define the __add__, __sub__, and __mul__ methods for the class, that's how. Each method takes two objects (the operands of +/-/*) as arguments and is expected to return the result of the computation.

这篇关于重载加法、减法和乘法运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆