
PYTHON — Composition in Python
The art of programming is the art of organizing complexity, of mastering multitude and avoiding its bastard chaos as effectively as possible. — Edsger W. Dijkstra
Insights in this article were refined using prompt engineering methods.

PYTHON — Building Regexes Summary in Python
# Composition in Python: A Brief Tutorial
In Python, composition models a “has a” relationship between classes. It represents a “part of” relationship, where one class is composed of another class. Let’s explore composition using an example of a Car composed of an Engine.
class Engine:
def __init__(self, cylinders, efficiency, weight):
self.cylinders = cylinders
self.efficiency = efficiency
self.weight = weight
def ignite(self):
# Code for igniting the engine
pass
class Car:
def __init__(self, brand, model, year, engine):
self.brand = brand
self.model = model
self.year = year
self.engine = engine
def turn_on(self):
self.engine.ignite()In the example above, the Car class has an attribute engine of type Engine. When a Car object is created, it must be supplied with a valid Engine object. The turn_on method of the Car class calls the ignite method of the Engine class.
We can access the Engine attributes from a global scope using the Car object. For example, my_car.engine.weight gives us access to the weight of the engine.
Composition provides a way to create more modular and reusable code. The Engine class can be used in other classes as well, as it is not strictly tied to the Car class.
When considering composition, one class can be a “component” of another “composite” class. In the example, the Car is the composite class made up of the Engine component.
Composition in Python provides a flexible way to design and structure classes, allowing for better code organization and reusability. It allows for the creation of complex objects by combining simpler objects, enhancing the maintainability and readability of the code.
To test your understanding, consider answering the following questions:
- What is the type of the
.engineattribute?
- The type is
Engine, as it is an instance of theEngineclass.
- Does the
.accelerate()method have access to the.efficiencyattribute?
- Yes, the
.accelerate()method can access theCar's.engineattribute, which contains the.efficiencyattribute.
- Can the
.ignite()method in theEngineclass access the.brandattribute?
- No, the
Engineclass does not have access to the.brandattribute of theCarclass due to the composition relationship.
In conclusion, composition in Python allows for the creation of complex objects by combining simpler objects. It promotes code organization, reusability, and modularity, enhancing the overall design of the code.
In this tutorial, we explored composition in Python, its implementation, and its benefits. Composition is a fundamental concept in object-oriented programming and plays a crucial role in designing robust and maintainable code.

