I have to add vector b to vector a. My class looks like this:
class Vector:
"""
creates a vector, which can be indexed, changed and added to another vector.
"""
def __init__(self,n=0,vec=[]):
"""
creating vecor
"""
self.n=n
self.vec=list(vec)
if len(vec)==0:
for i in range(n):
self.vec.append(0)
def __getitem__(self,i):
"""
indexing
"""
if i>=len(self.vec):
return(None)
else:
return(self.vec[i])
def __setitem__(self,i,val):
"""
changing
"""
self.vec[i]=val
I tried adding another method to my class called add:
def add(a,b):
"""
adds vector b to a
"""
x=0
for i in b:
a[x]=a[x] i
x =1
return (a)
Lets say I want this to work: a = Vector(vec = [1, 2, 3]) b = Vector(vec = [3, 4, 5])
c = Vector.add(a, b)
CodePudding user response:
What it looks like you're trying to do make a classmethod.
Something like this should work:
@classmethod
def add(cls, a,b):
"""
adds vector b to a
"""
return cls(vec=[x y for x, y in zip(a.vec, b.vec)])