What are magic methods

Magic methods in Python are special methods that have double underscores (dunder) before and after their names. These methods allow you to define the behavior of objects that belong to a class in a way that integrates seamlessly with Python's built-in features. For instance, these methods can be called automatically in certain situations, such as when an object is created, when it is added to another object, or when it is printed.

Some common magic methods include:

  • __init__: Called when an object is instantiated.
  • __str__: Defines the string representation of an object.
  • __repr__: Defines the official string representation of an object.
  • __add__: Defines the behavior of addition for objects.

Using magic methods makes your classes more intuitive and Pythonic.

class Vector: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return f"Vector({self.x}, {self.y})" def __add__(self, other): return Vector(self.x + other.x, self.y + other.y) v1 = Vector(2, 3) v2 = Vector(4, 5) result = v1 + v2 print(result) # Output: Vector(6, 8)

magic methods Python dunder methods object behavior