Module (85%)
Section (43%)

Let's try to write some code to see how composition works.

Look at the simple code presented in the editor pane.

The “Car” class is loosely coupled with the “engine” component. It’s a composite object.

The main advantages are:

  • whenever a change is applied to the engine object, it does not influence the “Car” class object structure;
  • you can decide what your car should be equipped with.

Our “Car” could be equipped with two different kinds of engine – a gas one or a diesel one. The developer's responsibility is to provide methods for both engine classes, named in the same way (here is thestart() method) to make it work in a polymorphic manner.

Run the code to confirm your expectations.


Code

class Car:
def __init__(self, engine):
self.engine = engine


class GasEngine:
def __init__(self, horse_power):
self.hp = horse_power

def start(self):
print('Starting {}hp gas engine'.format(self.hp))


class DieselEngine:
def __init__(self, horse_power):
self.hp = horse_power

def start(self):
print('Starting {}hp diesel engine'.format(self.hp))


my_car = Car(GasEngine(4))
my_car.engine.start()
my_car.engine = DieselEngine(2)
my_car.engine.start()
{{ dockerServerErrorMsg }} ×
{{ errorMsg }} ×
{{ successMsg }} ×