0
Are we passing any parameter to the init method
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)
7 Réponses
+ 2
self is a reference to the current instance of the class... When you call init though you do not pass it any argument for self.
Example: init(2, 3) and not init(self, 2, 3)
+ 1
In this case, yes we are passing three parameters to the __init__ method self, x value and y value.
+ 1
i believe self passes the instance of the class but I am not sure.
0
what is the value of self?
does it always stores the object which is calling it
0
then what are we passing in
0
then what are we passing in the add method
0
In the add method, we are passing second.
result = first + second
The add method is called when the + sign is encountered and whatever is listed after the + sign is the argument that is passed as other. So in this case, other is Vector2D(3, 9) because of this line of code: second = Vector2D(3, 9)
I copied the code from above to help us follow it. I added comments to help.
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) # first is assigned the value of (5, 7)
second = Vector2D(3, 9) # second is assigned the value of (3, 9)
result = first + second # second is the argument sent to __add__
print(result.x) # result.x is the sum of both x values, 5 added to 3 = 8
print(result.y) # result.y is the sum of both y values, 7 added to 9 = 16
I hope this helps. :-)