1

I have a question but I don't know exactly how to explain it, so let me put some code here:

class 2DVector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def multiply(self, scalar):
        self.x *= scalar
        self.y *= scalar

is it posible to do something like this

vector1 = 2DVector(1, 1).multiply(3)
# x == 3, y == 3

or do I always have to do it like this

vector2 = 2DVector(1, 1)
# x == 1, y == 1
vector2.multiply(3)
# x == 3, y == 3
2
  • 4
    Have you tried it? Did it work? Commented Sep 13, 2018 at 10:49
  • 1
    What's the point ? when you do vector1 = 2DVector(1, 1).multiply(3), vector1 will be None and and you'll lose x and y Commented Sep 13, 2018 at 10:50

3 Answers 3

2

Adding return self at the end of the multiply method allows you to use the first option:

class TwoDVector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def multiply(self, scalar):
        self.x *= scalar
        self.y *= scalar
        return self


if __name__ == '__main__':
    vector = TwoDVector(2, 3).multiply(2)
    # vector.x == 4, vector.y == 6
Sign up to request clarification or add additional context in comments.

Comments

2

They are equivalent in that they both scale the vector.

But your first example is not very useful it doesn't keep a reference to the class instance. Instead it keeps a reference to the return value of multiply (which is just None) so your vector reference is lost.

As mentioned you could modify multiply to return self.

You could also add a scale factor to the constructor:

class 2DVector:
    def __init__(self, x, y, scale=1):
        self.x = x
        self.y = y
        self.multiply(scale)

# scales vector to (3, 3)
vector1 = 2DVector(1, 1, 3)

1 Comment

... but OP might want to modify the code for multiply() to return self.
1

If you want to use vector2.multiply(3) directly, you need to adapt your method and return something.

    def multiply(self, scalar):
        self.x *= scalar
        self.y *= scalar
        return self

But I do not like this solution and prefer :

    def multiply(self, scalar):
        return 2DVector(self.x * scalar, self.y * scalar)

and treat vector as immutables objects.

Or keeping your first implementation and do

vector2 = 2DVector(1, 1)
# x == 1, y == 1
vector2.multiply(3)
# x == 3, y == 3

Comments

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.