What Is Composition In Python?
Assesses fundamental understanding of Python conventions, runtime behavior, and memory/performance considerations.
Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.
The composition is also a type of inheritance in Python. It intends to inherit from the base class but a little differently, i.e., by using an instance variable of the base class acting as a member of the derived class.
See the below diagram.
Python Interview Questions - Composition
To demonstrate composition, we need to instantiate other objects in the class and then make use of those instances.
class PC: # Base class
processor = "Xeon" # Common attribute
def __init__(self, processor, ram):
self.processor = processor
self.ram = ram
def set_processor(self, new_processor):
processor = new_processor
def get_PC(self):
return "%s cpu & %s ram" % (self.processor, self.ram)
class Tablet():
make = "Intel"
def __init__(self, processor, ram, make):
self.PC = PC(processor, ram) # Composition
self.make = make
def get_Tablet(self):
return "Tablet with %s CPU & %s ram by %s" % (self.PC.processor, self.PC.ram, self.make)
if __name__ == "__main__":
tab = Tablet("i7", "16 GB", "Intel")
print(tab.get_Tablet())
The output is:
Tablet with i7 CPU & 16 GB ram by Intel
Candidate Response Strategy & Interview Tips
- Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
- Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
- Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
- Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.