Dec 19, 2019 in Python

Q: What Is Composition In Python?

1 Answer

Dec 19, 2019
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")


The output is:

Tablet with i7 CPU & 16 GB ram by Intel
Click here to read more about Python
Click here to read more about Insurance

Related questions

Nov 15, 2019 in Continuous Integration
Aug 30 in Python
Aug 30 in Python