Composition
Introduction to OOP's
Class
Object
Constructor
Instance Variables
Class Variables
Instance Methods
self Keyword
Encapsulation
Public Members
Protected Members
Private Members
Inheritance
Single Inheritance
Multiple Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Hybrid Inheritance
super() Function
Polymorphism
Method Overriding
Duck Typing
Abstraction
Abstract Class
Abstract Method
Class Method
Static Method
Special Methods
_str_ Method
Operator Overloading
Composition
Aggregation
Association
Method Resolution Order
Object Class
issubclass() and isinstance()
Property Decorator
Setter Method with @property
Destructor
Inner Class
Complete Mini Example
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
Executing...
❌ Error:
✅ Output:
// Click Run ▶ to execute
🏋️ Test Yourself With Exercises
Take our quiz on Composition to test your knowledge.
Browse Quizzes »