what is composition in python

Solutions on MaxInterview for what is composition in python by the best coders in the world

showing results for - "what is composition in python"
Emelie
30 Oct 2017
1# It's when a class has a (is made-of) another class.
2# Example
3
4class Thing(object):
5    
6    def func(self):
7        print("Function ran from class Thing().")
8
9class OtherThing(object): # Note that I don't use inheritance to get the func() function
10    
11    def __init__(self):
12        self.thing = Thing() # Setting the composition, see how this class has-a another class in it?
13        
14    def func(self):
15        self.thing.func() # Just runs the function in class Thing()
16    
17    def otherfunc(self):
18        print("Function ran from class OtherThing().")
19
20random_object = OtherThing()
21
22random_object.func() # Still works, even though it didn't inherit from class Thing()
23random_object.otherfunc()