Back to Python
2026-04-135 min read

Encapsulation (Python Programming)

Learn Encapsulation (Python Programming) step by step with clear examples and exercises.

Title: Python Encapsulation - A full guide for Better Programming

Why This Matters

In programming, encapsulation is a fundamental concept that helps create modular and organized code. It allows us to hide the implementation details of an object and only expose its required functionality to the outside world. This practice improves code readability, reduces complexity, and enhances maintainability. Understanding encapsulation is crucial for writing efficient, scalable, and secure Python programs.

Prerequisites

Before diving into encapsulation, you should have a good understanding of the following topics:

  1. Basic Python syntax (variables, data types, operators)
  2. Functions in Python
  3. Classes and Objects in Python
  4. Access Modifiers (public, private, protected)

Core Concept

Encapsulation in Python can be achieved using classes and objects. By defining methods within a class as private, we can prevent them from being accessed directly outside the class. To make methods accessible to other parts of the program, we declare them as public.

class MyClass:

private method

def _private_method(self):

print("This is a private method")

public method

def public_method(self):

self._private_method()

print("This is a public method")


In the above example, `_private_method` is a private method that can only be accessed within the class. On the other hand, `public_method` is a public method that can be called from outside the class as well.

### Note on Python's approach to encapsulation:

Unlike some other programming languages, Python does not have explicit support for private members through naming conventions (e.g., using double underscores `__`). However, it is still possible to achieve encapsulation by defining methods and attributes with leading and trailing double underscores. These are known as "name mangling" and are treated as private within the class.

class MyClass:

name-mangled private attribute

__private_attribute = 0

def _get_private_attribute(self):

return self.__private_attribute

def _set_private_attribute(self, value):

self.__private_attribute = value


In this example, `__private_attribute` is a private attribute that can only be accessed using the `_get_private_attribute` and `_set_private_attribute` methods.

Worked Example

Let's create an example of encapsulation by defining a BankAccount class with private attributes (balance and pin) and public methods to deposit, withdraw, and check the account balance.

class BankAccount:
def __init__(self, pin, initial_balance=0):
self._pin = pin
self._balance = initial_balance

def deposit(self, amount):
if amount > 0:
self._balance += amount
print(f"Deposited {amount}. New balance: {self._balance}")
else:
print("Invalid deposit amount.")

def withdraw(self, amount):
if amount <= self._balance:
self._balance -= amount
print(f"Withdrew {amount}. Remaining balance: {self._balance}")
else:
print("Insufficient funds.")

def check_balance(self):
print(f"Current balance: {self._balance}")

Create a new bank account with PIN 1234 and an initial balance of 1000

my_account = BankAccount(1234, 1000)

Deposit 500 into the account

my_account.deposit(500)

Withdraw 700 from the account

my_account.withdraw(700)

Check the account balance

my_account.check_balance()


In this example, we've encapsulated the `balance` and `pin` attributes by making them private within the `BankAccount` class. The public methods provide a controlled interface for users to interact with the account without directly accessing these private attributes.

Common Mistakes

  1. Forgetting to make a method private: If you want to create a private method, ensure that it is defined within the class and not declared as public.
  2. Accessing private attributes directly: Avoid accessing private attributes outside of their respective methods. Instead, use public methods provided by the class for interaction.
  3. Not using name mangling correctly: When defining private attributes with leading and trailing double underscores, make sure to follow the correct naming convention (e.g., __private_attribute).
  4. Ignoring encapsulation altogether: Failing to encapsulate your code can lead to unorganized, hard-to-maintain, and potentially insecure programs.

Practice Questions

  1. Create a Person class with private attributes (name, age) and public methods for setting and getting the name and age.
  2. Modify the BankAccount class to include an overdraft limit. If a withdrawal exceeds the account balance plus the overdraft limit, the transaction should be processed as a loan with interest.
  3. Implement a Car class with private attributes (make, model, year) and public methods for setting and getting the make, model, and year. Add a method to calculate the car's age based on the current year.

FAQ

  1. Why should I use encapsulation in my Python programs?

Encapsulation helps create modular, organized, and secure code by hiding implementation details and providing a controlled interface for users to interact with objects. This practice improves readability, reduces complexity, and enhances maintainability.

  1. How can I make attributes private in Python?

In Python, you can't explicitly declare attributes as private like some other programming languages. However, you can achieve encapsulation by defining methods to access these attributes or using name mangling with leading and trailing double underscores (e.g., __private_attribute).

  1. What is the purpose of name mangling in Python?

Name mangling in Python is a technique used to create private attributes by modifying their names with leading and trailing double underscores. These name-mangled attributes are treated as private within the class and can only be accessed using special methods like _get_private_attribute and _set_private_attribute.

  1. How can I ensure that my encapsulation is secure in Python?

To make your encapsulation more secure, follow these practices:

  • Limit the number of public methods and attributes to only what's necessary for external interaction.
  • Implement proper input validation to prevent unauthorized access or manipulation of private data.
  • Use best practices for password storage if you're working with sensitive information like user accounts or login credentials.
Encapsulation (Python Programming) | Python | XQA Learn