encapsulation
Encapsulation is a fundamental concept in object-oriented programming (OOP) that involves bundling the data (attributes) and the behavior (methods) that operate on the data into a single entity, typically a class.
This concept helps protect an object’s internal state from direct or unauthorized access and modification by restricting access to some of its components. Instead of having direct access to data, you interact with it through an interface, such as methods, which can enforce rules or constraints.
Although Python doesn’t have strict access control like some other programming languages, it uses conventions such as prefixing attribute names with a single underscore (_
) to indicate that a given attribute is intended for internal use and not for external access.
Example
Here’s an example demonstrating encapsulation in Python:
class Car:
def __init__(self, make, model):
self._make = make
self._model = model
def display_info(self):
print(f"Car Make: {self._make}, Model: {self._model}")
@property
def model(self):
return self._model
@model.setter
def model(self, model):
self._model = model
# Usage
car = Car("Toyota", "Corolla")
car.display_info() # Output: Car Make: Toyota, Model: Corolla
car.model = "Camry"
print(car.model) # Output: Camry
In this example, the Car
class encapsulates the car’s make and model attributes. Both are non-public name, and you can only access or modify them through a property
.
Related Resources
Tutorial
Object-Oriented Programming (OOP) in Python
In this tutorial, you'll learn all about object-oriented programming (OOP) in Python. You'll learn the basics of the OOP paradigm and cover concepts like classes and inheritance. You'll also see how to instantiate an object from a class.
For additional information on related topics, take a look at the following resources:
- Python Classes: The Power of Object-Oriented Programming (Tutorial)
- Single and Double Underscores in Python Names (Tutorial)
- Python's property(): Add Managed Attributes to Your Classes (Tutorial)
- Intro to Object-Oriented Programming (OOP) in Python (Course)
- Object-Oriented Programming (OOP) in Python (Quiz)
- Class Concepts: Object-Oriented Programming in Python (Course)
- Inheritance and Internals: Object-Oriented Programming in Python (Course)
- Python Classes - The Power of Object-Oriented Programming (Quiz)
- Single and Double Underscore Naming Conventions in Python (Course)
- Single and Double Underscores in Python Names (Quiz)
- Managing Attributes With Python's property() (Course)
- Python's property(): Add Managed Attributes to Your Classes (Quiz)
By Leodanis Pozo Ramos • Updated May 6, 2025