Middle
What are magic methods in Python? Examples?
sobes.tech AI
Answer from AI
Magic methods in Python are special methods that start and end with double underscores (__method__). They allow overriding the behavior of objects, such as how they are created, compared, converted to a string, etc.
Examples of magic methods:
__init__(self, ...)— constructor of the object.__str__(self)— string representation of the object (forprint).__repr__(self)— official string representation of the object.__add__(self, other)— overriding the+operator.__len__(self)— returns the length of the object (forlen()).__getitem__(self, key)— access by index or key.
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)
v3 = v1 + v2
print(v3) # Vector(4, 6)
Magic methods make Python objects more flexible and integrated with the language.