Junior — Middle
Can you tell about magical methods you know in programming languages?
sobes.tech AI
Answer from AI
Magic methods in Python are special methods with double underscores at the beginning and end of the name (e.g., __init__, __str__). They allow overriding object behavior and integrating with the language syntax.
Some commonly used magic methods:
__init__(self, ...)— object constructor.__str__(self)— string representation of the object (forstr()andprint).__repr__(self)— official string representation of the object, useful for debugging.__len__(self)— returns the length of the object (forlen()).__getitem__(self, key)— access to elements by index or key.__setitem__(self, key, value)— setting a value by index or key.__iter__(self)— returns an iterator for the object.__call__(self, ...)— allows the object to be called as a function.__eq__(self, other)— equality comparison.
Example of using __str__ and __repr__:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name}, {self.age} years old"
def __repr__(self):
return f"Person(name={self.name!r}, age={self.age})"
p = Person("Ivan", 30)
print(str(p)) # Ivan, 30 years old
print(repr(p)) # Person(name='Ivan', age=30)
Magic methods allow creating more "Pythonic" and user-friendly code.