Advertisement

Magic Methods & Operator Overloading interview questions and answers

15 Magic Methods & Operator Overloading interview questions for Python roles, each with a model answer, examples and likely follow-ups.

15 questions
Advertisement

15 questions

Q11 Intermediate Save

How does __contains__ let you customize the behavior of the 'in' operator?

Defining __contains__(self, item) lets Python call it directly when evaluating `item in obj`, instead of falling back to iterating the whole object with __iter__ or __getitem__. This can be much faster for containers with efficient membership tests, like a class backed by a set or a database query.
class UserGroup:
    def __init__(self, user_ids):
        self._ids = set(user_ids)  # O(1) lookup
    def __contains__(self, user_id):
        return user_id in self._ids

group = UserGroup([1,2,3])
print(2 in group)  # True, O(1) via set
Real-world example
A permissions class backed by a set of allowed role IDs implements __contains__ so `if role in permissions:` checks run in constant time instead of scanning a list.
Likely follow-ups
  • What's the fallback behavior if __contains__ isn't defined?
  • How does this interact with __iter__ for custom iterables?
Data Types & Structures Iterators & the Iterator Protocol
Q12 Advanced Save

How does __bool__ (or the legacy __nonzero__) determine an object's truthiness, and what's the fallback if it's not defined?

__bool__(self) should return True or False and controls how an object behaves in boolean contexts like `if obj:` or `bool(obj)`. If __bool__ isn't defined, Python falls back to __len__, treating the object as False if its length is 0 and True otherwise. If neither is defined, all instances are considered truthy by default.
class Inventory:
    def __init__(self, items):
        self.items = items
    def __bool__(self):
        return len(self.items) > 0

inv = Inventory([])
if not inv:
    print('Inventory is empty')
Real-world example
A custom QuerySet-like class defines __bool__ to check whether any results exist without forcing a full evaluation or count of the entire result set, avoiding an expensive count query.
Likely follow-ups
  • What's the evaluation order between __bool__ and __len__?
  • Why might defining __len__ alone be sufficient?
Data Types & Structures Iterators & the Iterator Protocol
Q13 Intermediate Save

How do you implement custom attribute access with __getattr__ versus __getattribute__?

__getattr__(self, name) is only called as a fallback when normal attribute lookup fails (attribute not found through __dict__ or the class hierarchy) -- ideal for lazy attributes or proxies. __getattribute__(self, name) is called for every attribute access unconditionally, making it more powerful but riskier (easy to cause infinite recursion) since you must carefully delegate to super().__getattribute__() for normal attributes.
class LazyConfig:
    def __getattr__(self, name):
        print(f'Loading {name} on demand')
        value = load_from_disk(name)
        setattr(self, name, value)  # cache it
        return value

config = LazyConfig()
print(config.database_url)  # triggers lazy load only once
Real-world example
A configuration object lazily fetches and caches settings from a remote service only when first accessed, using __getattr__ to avoid an expensive upfront load of every possible setting.
Likely follow-ups
  • Why is __getattribute__ more dangerous to override than __getattr__?
  • How does this relate to descriptors?
Descriptors & Properties Metaclasses & Class Customization
Q14 Advanced Save

How does __slots__ interact with magic methods and instance attribute storage?

__slots__ declares a fixed set of attribute names, replacing the per-instance __dict__ with more memory-efficient fixed-size slots and preventing arbitrary new attributes from being set. It doesn't itself define magic methods, but it affects ones related to attribute storage: __getattr__/__setattr__ still work as fallbacks, but pickling, copying, and cached_property require special handling since there's no __dict__ to store extra state.
class Point:
    __slots__ = ('x', 'y')
    def __init__(self, x, y):
        self.x, self.y = x, y

p = Point(1, 2)
try:
    p.z = 3  # AttributeError: no __dict__, z not in __slots__
except AttributeError as e:
    print(e)
Real-world example
A high-volume data processing pipeline creating millions of small Point objects uses __slots__ to cut per-instance memory overhead significantly compared to default __dict__-based instances.
Likely follow-ups
  • How does __slots__ interact with inheritance from a class without __slots__?
  • Why can't you use cached_property with __slots__ directly?
Memory Management & Garbage Collection Descriptors & Properties
Q15 Beginner Save

How does __repr__ help with debugging when printing a list of custom objects?

When you print a container like a list, Python calls repr() on each element rather than str(), so a well-defined __repr__ ensures each object in a printed list, tuple, or dict is shown meaningfully instead of the default '<Point object at 0x7f...>' memory address representation.
class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y
    def __repr__(self):
        return f'Point({self.x}, {self.y})'

points = [Point(1,2), Point(3,4)]
print(points)  # [Point(1, 2), Point(3, 4)]
Real-world example
A debugging session inspecting a list of ORM model instances relies on each model's __repr__ showing its primary key and key fields instead of an opaque memory address.
Likely follow-ups
  • Why does print(list_of_objects) use repr() and not str()?
  • What makes a 'good' __repr__ according to Python conventions?
Debugging & Profiling Data Types & Structures

Showing 11–15 of 15