Home Tutorials Python OOP Concepts Composition
Composition

Composition


30. Composition

Composition is a design approach where one class contains an object of another class to reuse functionality. It models a "has-a" relationship instead of an "is-a" relationship.

Syntax

class A:
    pass

class B:
    def __init__(self):
        self.obj = A()

Example

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
Example

🏋️ Test Yourself With Exercises

Take our quiz on Composition to test your knowledge.

Browse Quizzes »