我想使用 add 方法运算符重载添加两个n个维的向量。用户将输入两个向量的元素。我不明白如何将向量定义为单个对象。 在我的示例代码中,向量s1和s2具有2个定义的值。我希望向量从具有N个维度的用户那里获取输入,然后使用class和 add 方法添加它们,我只能使用功能而不使用类和对象,但是它是用于家庭作业的,需要使用类。例如:
s1 = [float(x) for x in input().split()]
s2= [float(x) for x in input().split()]
s3=s1+s2
我一无所知,将不胜感激。
class Student :
def __init__(self,m1,m2) :
self.m1=m1
self.m2=m2
def __add__(self,other) :
m1=self.m1+other.m1
m2=self.m2+other.m2
s3=Student(m1,m2)
return s3
s1=Student(58,69)
s2=Student(60,65)
s3=s1+s2
print(s3.m1,s3.m2)
答案 0 :(得分:0)
如果允许您使用numpy
,则以下解决方案将起作用:
import numpy as np
x = np.array([float(x) for x in "1 2 3".split()])
y = np.array([float(x) for x in "3 4 5".split()])
print(x)
# [1. 2. 3.]
print(y)
# [3. 4. 5.]
print(x+y)
# [4. 6. 8.]
class Student:
def __init__(self, data):
self.data = data
def __add__(self, other):
return Student(self.data+other.data)
student_x = Student(x)
student_y = Student(y)
print((student_x+student_y).data)
# [4. 6. 8.]