Composition Example

Use composition by placing one object inside another to build complex behavior.

IntermediateTopic: Object-Oriented Programs
Back

Python Composition Example Program

This program helps you to learn the fundamental structure and syntax of Python programming.

Try This Code
# Program to demonstrate composition

class Engine:
    def start(self):
        print("Engine started")


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

    def drive(self):
        self.engine.start()
        print("Car is moving")


c = Car()
c.drive()
Output
Engine started
Car is moving

Understanding Composition Example

Car is composed of an Engine object; it delegates the 'start' behavior to Engine instead of inheriting from it.

Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.

Table of Contents