...

/

Solution Review: Overload the Operators for Vectors

Solution Review: Overload the Operators for Vectors

The solution to the 'Overload the Operators for Vectors' challenge.

Overloading the negation operator

Press + to interact
class Vector():
def __init__(self, vector):
self.vector = vector
def print(self):
print(list(self.vector))
# Overloading unary - operator
def __neg__(self):
return Vector(-x for x in self.vector)
v1 = Vector([-1, 2])
v2 = Vector([-3,-4])
# Reversing two vectors
v3 = -v1
v4 = -v2
v3.print()
v4.print()

Overloading the - operator just needs a one-line implementation. Look at line 11. To ...

Access this course and 1400+ top-rated courses and projects.