Middle
What magical methods exist in Python?
sobes.tech AI
Answer from AI
Magic methods in Python are special methods that start and end with double underscores (e.g., __init__, __str__). They allow overriding the behavior of built-in operations and integrating with the language syntax.
Main groups of magic methods:
- Initialization and object creation:
__new__,__init__ - Object representation:
__str__,__repr__ - Arithmetic operations:
__add__,__sub__,__mul__,__truediv__, etc. - Comparison operations:
__eq__,__lt__,__gt__,__le__,__ge__,__ne__ - Attribute access management:
__getattr__,__setattr__,__delattr__ - Iterators and generators:
__iter__,__next__ - Context managers:
__enter__,__exit__ - Indexing and slicing:
__getitem__,__setitem__,__delitem__ - Calling an object as a function:
__call__
Example of overriding an arithmetic operator and string representation:
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 __repr__(self):
return f"Vector({self.x}, {self.y})"
v1 = Vector(1, 2)
v2 = Vector(3, 4)
print(v1 + v2) # Vector(4, 6)
Magic methods are widely used for implementing design patterns and extending class capabilities.