python composition code example
Example 1: what is composition in python
class Thing(object):
def func(self):
print("Function ran from class Thing().")
class OtherThing(object):
def __init__(self):
self.thing = Thing()
def func(self):
self.thing.func()
def otherfunc(self):
print("Function ran from class OtherThing().")
random_object = OtherThing()
random_object.func()
random_object.otherfunc()
Example 2: function composition python
def compose2(f, g):
return lambda x: f(g(x))
Example 3: composition in python
In composition one of the classes is composed of one or more instance of other classes. In other words one class is container and other class is content and if you delete the container object then all of its contents objects are also deleted