Module 4 Lesson 5: Encapsulation and Data Hiding
·Programming

Module 4 Lesson 5: Encapsulation and Data Hiding

Protect your data. Learn how to use 'private' attributes to prevent accidental changes and ensure your objects follow their own rules.

Module 4 Lesson 5: Encapsulation and Data Hiding

In the previous lessons, we could change an object's data from anywhere: my_account.balance = 1000000. This is dangerous! In professional software, we want to protect the data inside an object and only allow it to be changed through specific methods. This principle is called Encapsulation.

Lesson Overview

In this lesson, we will cover:

  • The Problem: Accidental and illegal data changes.
  • Private Attributes: Using the double underscore __.
  • Getters and Setters: The safe way to read and write data.
  • Encapsulation in Practice: Building a secure Bank Account.

1. The Power of the Double Underscore (__)

In Python, if you name an attribute starting with two underscores, Python treats it as "private." It becomes much harder to access from outside the class.

class Account:
    def __init__(self, owner, balance):
        self.owner = owner
        self.__balance = balance # This is now PRIVATE

my_acct = Account("Sara", 500)
# print(my_acct.__balance) # This will cause an AttributeERROR!

2. Getters and Setters

Since we can't touch __balance directly, how do we use it? We create Methods to handle it for us. These are often called "Getters" (to see the data) and "Setters" (to change the data).

class Account:
    def __init__(self, owner, balance):
        self.owner = owner
        self.__balance = balance

    def get_balance(self):
        return self.__balance # A "Safe" look at the data

    def deposit(self, amount):
        if amount > 0:
            self.__balance += amount
            print(f"Added ${amount}. New balance: ${self.__balance}")
        else:
            print("Error: You cannot deposit a negative amount!")

my_acct = Account("Sara", 500)
my_acct.deposit(100)
print(my_acct.get_balance())

3. Why Encapsulate?

  1. Validation: A "Setter" method can check if the data is valid (like preventing negative deposits).
  2. Security: You can prevent other programmers from accidentally breaking your logic.
  3. Flexibility: If you decide to change how your balance is calculated later, you only change the method, not every place the balance is used.

4. "Private" in Python vs. Other Languages

Unlike some languages (like Java), Python doesn't strictly block you from private data; it just renames it behind the scenes (this is called "Name Mangling"). However, as a programmer, seeing __ is a universal signal that says: "HANDS OFF! Use the methods instead."


Practice Exercise: The Secure Login

Create a file named secure_user.py.

  1. Define a class User.
  2. In __init__, set username (public) and __password (private).
  3. Add a method update_password(old_pw, new_pw) that only changes the password if the old_pw matches the current one.
  4. Add a method show_info() that prints the username but never prints the password.
  5. Test it by trying to change the password with a wrong old password.

Quick Knowledge Check

  1. What symbols do we use to make an attribute private in Python?
  2. What is a "Getter" method?
  3. Give one reason why you would want to hide data from the rest of the program.
  4. Can you access a private variable __x from outside the class using my_obj.__x?

Key Takeaways

  • Encapsulation bundles data and methods together and limits access.
  • Private attributes start with __ (double underscore).
  • Use methods to validate and control how data is updated.
  • Encapsulation makes your code more secure and harder to break.

What’s Next?

We’ve learned how to build a single class and protect its data. But what if you have multiple classes that share common traits? In Lesson 6, we’ll explore Inheritance—how to build new classes based on existing ones!

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn