1

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

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

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 class

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.