← Python Programming
Object-oriented Python and projects · 15 MIN

Inheritance and composition

Inheritance and composition

Inheritance lets a class extend another class, but deep inheritance trees are hard to maintain. Composition builds larger behavior from smaller objects and is often more flexible. Override methods only when the subtype can honor the expected behavior.

Try it yourself

Change the example, run it, and explain the result in your own words. Then create one variation of your own.

Key idea

Use the example as a starting point, not something to memorize. Practise, inspect the result and make small improvements.

Code example

class EmailNotifier:
    def send(self, message):
        print("Email:", message)

class Report:
    def __init__(self, notifier):
        self.notifier = notifier

    def publish(self):
        self.notifier.send("Report ready")