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?

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 []
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

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.