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

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

问题描述

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

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.

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

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