Inheritance and composition

But this is just half of the story, OOP is much more powerful. We have two main design constructs to exploit: inheritance and composition.

Inheritance means that two objects are related by means of an Is-A type of relationship. On the other hand, composition means that two objects are related by means of a Has-A type of relationship. It's all very easy to explain with an example:

# oop/class_inheritance.pyclass Engine:    def start(self):        pass    def stop(self):        passclass ElectricEngine(Engine):  # Is-A Engine    passclass V8Engine(Engine):  # Is-A Engine    passclass Car:    engine_cls = Engine    def __init__(self):        self.engine = self.engine_cls()  # Has-A Engine    def start(self):        print( 'Starting engine {0} for car {1}... Wroom, ...

Get Learn Web Development with Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.