+ 5
please help me to understand this code please...it belongs to python ...
class Vector2D: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Vector2D(self.x + other.x, self.y + other.y) first = Vector2D(5, 7) second = Vector2D(3, 9) result = first + second print(result.x) print(result.y)
2 Answers
+ 1
I littered a bunch of comments in case some of it is unclear.
class Vector2D:
# Define constructor, or how to initialize a Vector2D instance.
def __init__(self, x, y):
self.x = x
self.y = y
# Define meaning for the '+' operator between a Vector2D instance and something else.
def __add__(self, other):
return Vector2D(self.x + other.x, self.y + other.y)
first = Vector2D(5, 7) # Create a vector where x = 5, y = 7.
second = Vector2D(3, 9) # Create a vector where x = 3, y = 9.
result = first + second # Create a vector where x = 5 + 3 = 8, y = 7 + 9 = 16
print(result.x) # print 8
print(result.y) # print 16
It would be nicer if you had a more specific question. Nothing stands out to me as particularly confusing.
0
in addition to the above post, study operator overloading.