I have my first task on python class:
- Create a module
vectors.py - It will be a class definition
MyVector - constructor will accept one parameter, which will be one-dimensional array.
get_vector()method returns one-dimensional array containing the elements of the vector.- using a special method
__ mul__(self, other)implement the dot product of two objects of type MyVector. The output is a scalar (a single number).
Now it's seems like this:
class MyVector:
def __init__(self,vector=[]):
self.vector=vector
def get_vector(self):
return (self.vector)
def __mul__(self,other):
dot=sum(p*q for p,q in zip(self.vector, WHAT IS HERE?))
return(dot)
I have first vector, but how can I initialize second?
Matthew Trevor
15k6 gold badges41 silver badges52 bronze badges
asked Sep 30, 2012 at 13:15
JohnDow
1,3324 gold badges24 silver badges40 bronze badges
1 Answer 1
If you assume that the other parameter for the special __mul__ method is an instance of MyVector, then that instance will also have an attribute named vector which you can access:
def __mul__(self,other):
dot=sum(p*q for p,q in zip(self.vector, other.vector))
return (dot)
and don't use [] as default value in function arguments, use something like this :
def __init__(self,vector=None):
self.vector=vector if vector else []
Ashwini Chaudhary
252k60 gold badges479 silver badges520 bronze badges
answered Sep 30, 2012 at 13:17
buc
6,3561 gold badge38 silver badges52 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Jon Clements
Using
None as a "sentinel", then self.vector = vector if vector is not None else [] is perhaps more correct. Also, more for the OP, it's probably best to use other.get_vector() to preserve duck typing and preserve an interface to a classlang-py