Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
Filter by Categories
About Article
Analyze Data
Archive
Best Practices
Better Outputs
Blog
Code Optimization
Code Quality
Command Line
Daily tips
Dashboard
Data Analysis & Manipulation
Data Engineer
Data Visualization
DataFrame
Delta Lake
DevOps
DuckDB
Environment Management
Feature Engineer
Git
Jupyter Notebook
LLM
LLM
Machine Learning
Machine Learning
Machine Learning & AI
Manage Data
MLOps
Natural Language Processing
NumPy
Pandas
Polars
PySpark
Python Tips
Python Utilities
Python Utilities
Scrape Data
SQL
Testing
Time Series
Tools
Visualization
Visualization & Reporting
Workflow & Automation
Workflow Automation

Inheritance vs. Composition: Choose the Right Design Approach

Table of Contents

Inheritance vs. Composition: Choose the Right Design Approach

In Python, inheritance is used when one class is a specialized version of another class. In the following example, the WholeMilk class represents a specific type of milk.

On the other hand, composition is used when one class forms a “has-a” relationship with another class. In the following example, the MilkTea class contains an instance of Milk as an attribute.

By using composition, the MilkTea class can use the functionalities of the Milk class without inheriting its attributes and methods. This design enables:

  • Substituting the milk implementation without impacting the MilkTea class.
  • Reusing the Milk class in other classes, such as Cake.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top

Work with Khuyen Tran

Work with Khuyen Tran