in Python by
What Is Composition In Python?

1 Answer

0 votes
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

Related questions

0 votes
0 votes
asked Dec 7, 2020 in JAVA by SakshiSharma
0 votes
asked Oct 12 in Python by rajeshsharma