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
return "%s cpu & %s ram" % (self.processor, self.ram)
make = "Intel"
def __init__(self, processor, ram, make):
self.PC = PC(processor, ram) # Composition
self.make = make
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")
The output is:
Tablet with i7 CPU & 16 GB ram by Intel