Middle+
What are magic methods (dunder methods)? Why are they called magic?
sobes.tech AI
Answer from AI
Magic methods in Python are special methods whose names start and end with double underscores (e.g., __init__, __str__, __add__). They are called "magic" because they allow changing the behavior of objects and classes at the language level, such as defining how an object is created, converted to a string, compared, or interacts with operators.
Example:
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __str__(self):
return f"Vector({self.x}, {self.y})"
v1 = Vector(1, 2)
v2 = Vector(3, 4)
print(v1 + v2) # Outputs: Vector(4, 6)
Here, __add__ allows using the + operator to add Vector objects, and __str__ outputs them in a readable format.