Imagine a bank account where you can check your balance but can’t modify it directly. This is an example of encapsulation—hiding sensitive data and only allowing controlled access.
Encapsulation in Python uses private attributes and getter/setter methods to restrict direct modification of data, improving security and organization.
💡 Analogy: A capsule protects medicine inside it. Encapsulation in programming protects data from being changed accidentally.
By the end of this lesson, you will be able to:
Understand encapsulation in Object-Oriented Programming.
Use access modifiers (public, private).
Implement getter and setter methods to control access to attributes.
Encapsulation – Restricting direct access to an object’s data, allowing controlled interaction.
Public attributes – Attributes that can be accessed freely (self.name).
Private attributes (__var) – Variables that cannot be accessed directly from outside a class.
Getters and setters – Methods that retrieve and modify private attributes safely.
Data protection – Preventing unintended modifications to an object’s internal state.
Example 1: Public and Private Attributes
class BankAccount:
def __init__(self, owner, balance):
self.owner = owner # Public attribute
self.__balance = balance # Private attribute
def get_balance(self):
return self.__balance
account = BankAccount("Alice", 1000)
print(account.owner) # Output: Alice
print(account.get_balance()) # Output: 1000
🔗 Practice on W3Schools: Encapsulation – Learn how to protect class attributes using private variables.
🔗 Try It Online: Run Your Code Here – Test your Python code instantly.
1️⃣ Basic Challenge:
Create a BankAccount class with owner and balance attributes, keeping balance private.
2️⃣ Extended Challenge:
Add deposit() and withdraw() methods to modify the balance safely.
3️⃣ Advanced Challenge:
Write a program that uses getter and setter methods to control access to private attributes.
Write the example from this lesson, ensuring you include:
✅ A class with private attributes
✅ Getter and setter methods
✅ Calling these methods to access and modify attributes
Read the example code before writing