in Python by
Q:
What Is Composition In Python?

1 Answer

0 votes
by
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
Click here to read more about Python
Click here to read more about Insurance

Related questions

0 votes
asked Dec 14, 2019 in React JS by AdilsonLima
0 votes
asked Jan 18 in Python by SakshiSharma
0 votes
asked Jan 1 in Python by SakshiSharma
0 votes
0 votes
asked Aug 30, 2020 in Python by sharadyadav1986
0 votes
asked Aug 30, 2020 in Python by sharadyadav1986
...