Lesson 29 of 55 · Python
Magic Methods and Dunder
Duration: 20 minutes
Lesson 29 of 55 · Python
Duration: 20 minutes
__).\n\npython\nclass Vector:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n def __repr__(self):\n return f'Vector({self.x}, {self.y})'\n def __len__(self):\n return 2\n def __add__(self, other):\n return Vector(self.x + other.x, self.y + other.y)\n\nv1 = Vector(1, 2)\nv2 = Vector(3, 4)\nprint(v1) # Vector(1, 2)\nprint(len(v1)) # 2\nprint(v1 + v2) # Vector(4, 6)\n\n\nImplementing the appropriate dunder methods makes your classes feel like native Python types.\n