Skip to content

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. Python also supports name mangling with double underscores (__): an attribute like __attr is internally renamed to _ClassName__attr, providing protection against accidental access or overriding in subclasses.

Example

Here’s an example demonstrating encapsulation in Python:

Language: 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 names, and you can only access or modify them through a property.

OOP in Python 3

Tutorial

Object-Oriented Programming (OOP) in Python

Learn object-oriented programming in Python: the OOP paradigm, classes and inheritance, and how to instantiate objects from a class.

intermediate python

For additional information on related topics, take a look at the following resources:

Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.


By Leodanis Pozo Ramos • Updated July 7, 2026 • Reviewed by Dan Bader