11How does method resolution order (MRO) work with multiple inheritance in Python, and how do you inspect it when debugging unexpected method calls?
For normal class-based method lookup, Python follows the class's method resolution order, or MRO, computed using C3 linearization. The first definition found along that order is selected. A subclass takes precedence over its ancestors, declared base order constrains precedence, and C3 preserves a consistent ordering through multiple inheritance, including diamonds. For class D(B, C), where B and C both derive from A and impose no conflicting order, the MRO is D, B, C, A, object. A hierarchy with incompatible ordering constraints is rejected with TypeError. I inspect D.__mro__ or D.mro() rather than guess. super() continues lookup after the current class in the actual instance's MRO; it does not mean a permanently chosen immediate parent. Cooperative methods therefore need compatible calling conventions and should consistently delegate with super when the design expects every class in the chain to participate.
class A:
def process(self):
return "A"
class B(A):
def process(self):
return f"B -> {super().process()}"
class C(A):
def process(self):
return f"C -> {super().process()}"
class D(B, C):
def process(self):
return f"D -> {super().process()}"
print("MRO:", [cls.__name__ for cls in D.__mro__])
print("Call output:", D().process())
Try answering this question with an AI coach
12How do inheritance, MRO and super() work?
Python resolves attributes through the Method Resolution Order, which is visible with ClassName.__mro__. In single inheritance it is straightforward, but in multiple inheritance Python uses C3 linearization to create a consistent order. super() does not mean 'call my parent' exactly; it means 'call the next implementation in the MRO'. That makes cooperative multiple inheritance possible when methods accept compatible arguments and each class calls super() correctly.
class A:
def save(self):
print("A")
class B(A):
def save(self):
print("B")
super().save()
class C(A):
def save(self):
print("C")
super().save()
class D(B, C):
pass
D().save() # B, C, A
Try answering this question with an AI coach
13What is the difference between iterable, iterator and generator?
An iterable is any object that can return an iterator from iter(), such as a list or a file object. An iterator is the stateful object that implements __next__ and raises StopIteration when exhausted. A generator is a convenient way to create an iterator with yield or a generator expression. Generators are memory-efficient because they produce values lazily, but they are usually one-shot and cannot be indexed like a list.
def read_lines(path):
with open(path, encoding="utf-8") as file:
for line in file:
yield line.strip()
Try answering this question with an AI coach
14What is a context manager and why is with useful?
A context manager defines enter and exit behavior with __enter__ and __exit__, or can be created with contextlib.contextmanager. The with statement makes resource management explicit and reliable: files are closed, locks are released and transactions can commit or roll back even when exceptions happen. __exit__ receives exception information and may suppress the exception by returning true, though suppressing errors should be used carefully.
from contextlib import contextmanager
with open("data.txt", encoding="utf-8") as file:
data = file.read()
@contextmanager
def temporary_setting():
print("enter")
try:
yield
finally:
print("exit")
Try answering this question with an AI coach
15How do shallow copy and deep copy differ?
Assignment creates another binding to the same object; it is not a copy. A shallow copy, such as list(original), creates a new outer list whose elements still reference the original nested objects. If a = [[1], [2]] and b = a.copy(), b[0].append(3) changes the inner list visible through a, but b[0] = [9] changes only b's outer slot. copy.deepcopy recursively copies supported nested state and uses a memo to handle cycles and preserve repeated references within the copied graph. It can be expensive and may copy more than intended. Immutable objects may be reused, classes can customize copying, and external resources such as sockets or database connections do not become independent usable resources merely through deepcopy. I choose the minimum copy boundary needed for the intended ownership and mutations rather than treating deep copy as a universal isolation mechanism.
from copy import copy, deepcopy
original = [[1], [2]]
shallow = copy(original)
deep = deepcopy(original)
original[0].append(99)
print(shallow) # [[1, 99], [2]]
print(deep) # [[1], [2]]
Try answering this question with an AI coach