+ 3

Working mechanism of Dunders:

If we have an expression "x + y" and x is an instance of class K, then Python will check the class definition of K. If K has a method __add__ it will be called with x.__add__(y), otherwise we will get an error message. class Vector2D: def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __add__(self, other): return Vector2D(self.x + other.x, self.y + other.y, self.z + other.z) first = Vector2D(5, 7, 8) second = Vector2D(3, 9, 12) result = first + second print(result.x) print(result.y) print(result.z) Output: 8 16 20

9th Nov 2016, 6:23 PM
ABHI
ABHI - avatar
1 ответ
0
and if you implement __repr__ and __str__, you can see it in the interactive session and you can use print on it, respectively
13th Nov 2016, 9:16 AM
Amaras A
Amaras A - avatar