Skip to main content

Command Palette

Search for a command to run...

🛡️Encapsulation in Python — Protecting Your Data

Published
6 min read
🛡️Encapsulation in Python — Protecting Your Data

In the previous articles, we learned how classes and objects help us structure our programs in a better way.
Now, let’s move one step forward and understand another important concept in Object-Oriented Programming — Encapsulation.

Encapsulation is one of those topics that sounds complex at first, but once you relate it to real life, it becomes very easy to understand.


🤔 What Is Encapsulation?

Encapsulation means binding data and the methods that operate on that data together, and restricting direct access to some parts of the data.

In simple words:

Encapsulation helps us protect data and control how it is accessed or modified.

We don’t allow anyone to change important data directly.
Instead, we provide safe ways to access or update it.


🏦 Real-Life Example: Bank Account

Think about your bank account.

Can you directly go to the bank’s database and change your balance?
No.

What can you do instead?

  • Deposit money

  • Withdraw money

  • Check balance

Your balance is hidden, and you can access it only through proper actions.

This is exactly how encapsulation works.


🧪 Bank Account Example in Python

class BankAccount:
    def __init__(self, balance):
        self.__balance = balance   # private variable

    def get_balance(self):
        return self.__balance

    def deposit(self, amount):
        if amount > 0:
            self.__balance += amount

    def withdraw(self, amount):
        if amount <= self.__balance:
            self.__balance -= amount

Here:

  • __balance is not accessible directly

  • The user must use deposit() or withdraw()

  • Rules are applied automatically

This makes the program safe and realistic.


📱 Real-Life Example: Mobile Phone

Think about your mobile phone.

You can:

  • Increase or decrease volume

  • Open apps

  • Lock the phone

But you cannot:

  • Directly control battery internals

  • Modify hardware settings

The internal system is hidden, and you interact only through buttons and options.

This is encapsulation in real life.


🏫 Real-Life Example: Student Marks

In a school system:

  • Students should not directly change their marks

  • Only teachers can update marks

  • Students can only view them


Python Example

class Student:
    def __init__(self, name, marks):
        self.name = name
        self.__marks = marks

    def get_marks(self):
        return self.__marks

    def update_marks(self, new_marks):
        if 0 <= new_marks <= 100:
            self.__marks = new_marks

Here:

  • Marks are protected

  • Invalid values are prevented

  • Data remains consistent


🔐 Public, Protected, and Private Variables

Python controls access using naming conventions.

Public Variable

self.name

Accessible anywhere.


Protected Variable

self._email

Should not be accessed directly, but still possible.


Private Variable

self.__password

Strongly protected and used for sensitive data.


🔍 Difference Between Public, Protected, and Private Variables

Now that we’ve seen all three types, let’s clearly understand how they differ, especially in initialization and access.

🟢 Public Variables

Public variables are created normally and can be accessed from anywhere.

Example:

class User:
    def __init__(self, name):
        self.name = name   # public variable

Usage:

u = User("Alice")
print(u.name)   # Accessible

👉 Public variables are best used when the data is safe to expose, like names or IDs.


🟡 Protected Variables

Protected variables are defined using a single underscore _.

Example:

class User:
    def __init__(self, email):
        self._email = email   # protected variable

Usage:

u = User("abc@gmail.com")
print(u._email)   # Accessible, but not recommended

👉 Protected variables can be accessed, but by convention:

  • They are meant to be used inside the class or its child classes

  • Developers understand: “Use this carefully”


🔴 Private Variables

Private variables use double underscore __.

Example:

class User:
    def __init__(self, password):
        self.__password = password   # private variable

Usage:

u = User("secret123")
# print(u.__password)   ❌ Error

Private variables:

  • Cannot be accessed directly

  • Are internally renamed by Python (name mangling)

  • Must be accessed using methods

Correct way:

class User:
    def __init__(self, password):
        self.__password = password

    def get_password(self):
        return self.__password

🧠 What’s the Real Difference?

TypeSyntaxDirect AccessIntended Use
Publicself.name✅ YesOpen data
Protectedself._email⚠️ Yes (not recommended)Internal use
Privateself.__password❌ NoSensitive data

⚠️ Important Note About Private Variables

To make a variable truly private in Python, you must use double underscore (__), not a single underscore.

❌ This is NOT private:

self._password

This is only protected, not private.
It can still be accessed directly.


✅ This IS private:

self.__password

This tells Python to:

  • Apply name mangling

  • Prevent direct access

  • Treat the variable as internal to the class


🔍 Why Double Underscore Matters

Python uses the double underscore to change the variable name internally.

Example:

self.__password

Internally becomes:

_User__password

This is why:

user.__password   # ❌ Error

But:

user._User__password   # ⚠️ Technically possible, but not recommended

👉 This mechanism exists to discourage misuse, not to break your code.


🧠 Simple Rule to Remember

  • _variable → Protected (use carefully)

  • __variable → Private (use double underscore only)

  • Never assume _ means private — it does not

💡 Key Takeaway

  • Public → Anyone can access

  • Protected → Access allowed, but use carefully

  • Private → Access only through methods

This system helps us control data, prevent misuse, and write professional code.

⚠️ Why Encapsulation Is Important

Without encapsulation, this could happen:

account.balance = -5000

Which makes no sense.

Encapsulation prevents:

  • Invalid data

  • Accidental changes

  • Logical errors


🧠 Important Point to Remember

Encapsulation does not mean hiding everything.

It means:

  • Hide important data

  • Allow controlled access using methods


💡 Why Encapsulation Matters in Real Projects

Encapsulation helps in:

  • Writing clean code

  • Protecting data

  • Avoiding bugs

  • Managing large applications

  • Working in teams

That’s why encapsulation is used in real-world software systems.


📝 Practice Questions

Try answering these:

  1. What is encapsulation in simple words?

  2. Why should data not be accessed directly?

  3. Create a User class with a private password.

  4. What is the difference between public and private variables?


🏁 Conclusion

In this article, we learned:

  • What encapsulation is

  • Why data protection is important

  • How Python implements encapsulation

  • How real-life systems use encapsulation

Encapsulation helps us write secure, logical, and maintainable code.


🔜 What’s Next?

In the next article, we’ll learn about Inheritance in Python — how one class can reuse and extend another class.

👉 Article 4: Inheritance in Python — Reusing Code Efficiently

Keep learning 🚀

Mastering OOP in Python

Part 3 of 6

In this series, I will guide you through the core concepts of OOP in Python from understanding classes, objects, constructors to master inheritance, polymorphism, encapsulation, abstraction. Articles includes examples, clear explanations, source code

Up next

Inheritance in Python – Building New Classes from Existing Ones

When we write programs, we often notice something interesting:many objects share common features. For example: A Student and a Teacher both have a name and an email. A Car and a Bike are both vehicles. A Dog and a Cat are both animals. Instead o...