I am new to python OOP programming. I was doing this tutorial on overloading operators from here(Scroll down to operator Overloading). I couldn't quite understand this piece of code. I hope somebody will explain this in detail. To be precise I didn't understand the how are 2 objects being added here and what are the lines
def __str__(self):
return 'Vector (%d, %d)' % (self.a, self.b)
def __add__(self,other):
return Vector(self.a + other.a, self.b + other.b)
doing here?
#!/usr/bin/python
class Vector:
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return 'Vector (%d, %d)' % (self.a, self.b)
def __add__(self,other):
return Vector(self.a + other.a, self.b + other.b)
v1 = Vector(2,10)
v2 = Vector(5,-2)
print v1 + v2
This generates an output Vector(7,8). How are the objects v1 and v2 being added here?
v1 + v2
is treated as a call to v1.__add__(v2)
, with self == v1
and other == v2
.
This is the Python data model and your question is answered here
Basically when v1 + v2
is performed python internally performs v1.__add__(v2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With