Q1. What are magic (dunder) methods in Python?
Magic methods are special methods with double underscores (e.g., __init__, __str__) that allow classes to emulate built-in types and define behavior for operators, context managers, iteration, etc.
They are called implicitly by Python in certain situations.
They are called implicitly by Python in certain situations.
Q2. What is the purpose of __str__ and __repr__?
__str__ is called by str() and print() for a user-friendly string representation.
__repr__ is called by repr() and is meant to be an unambiguous representation, often used for debugging.
If __str__ is missing, __repr__ is used as a fallback.
__repr__ is called by repr() and is meant to be an unambiguous representation, often used for debugging.
If __str__ is missing, __repr__ is used as a fallback.
Q3. What are the magic methods for arithmetic operators?
For addition: __add__, subtraction: __sub__, multiplication: __mul__, division: __truediv__, etc.
There are also reversed methods (__radd__) and in-place (__iadd__).
Example:
There are also reversed methods (__radd__) and in-place (__iadd__).
Example:
a + b calls a.__add__(b)Q4. How do you make an object callable?
Define the __call__ method in the class. The instance can then be called like a function.
Example:
Example:
class Adder:
def __init__(self, n):
self.n = n
def __call__(self, x):
return self.n + x
add5 = Adder(5)
print(add5(3)) # 8Q5. What are the magic methods for context managers?
__enter__ and __exit__ are used to implement context managers (with statement).
__enter__ sets up the context, __exit__ handles cleanup.
Example:
__enter__ sets up the context, __exit__ handles cleanup.
Example:
with MyContext() as ctx:
# use ctx