Bird
Raised Fist0
Pythonprogramming~10 mins

Purpose of encapsulation in Python - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Purpose of encapsulation
Define class with private data
Create object of class
Access data only via methods
Data is protected from outside changes
Safe and controlled data handling
Encapsulation means hiding data inside a class and only allowing access through methods to keep data safe and controlled.
Execution Sample
Python
class BankAccount:
    def __init__(self, balance):
        self.__balance = balance
    def deposit(self, amount):
        self.__balance += amount
    def get_balance(self):
        return self.__balance
This code creates a bank account class that hides the balance and allows changes only through deposit and get_balance methods.
Execution Table
StepActionVariable/MethodValue/ResultExplanation
1Create objectaccount = BankAccount(100)account.__balance is hiddenBalance is set to 100 but hidden with __ prefix
2Call depositaccount.deposit(50)balance updated to 150Deposit method adds 50 to hidden balance
3Call get_balanceaccount.get_balance()returns 150Access balance safely via method
4Try direct accessaccount.__balanceAttributeErrorDirect access to __balance is blocked
5Try name mangling accessaccount._BankAccount__balance150Private variable can be accessed but should not be
6End--Encapsulation protects data from accidental changes
💡 Encapsulation stops direct access to private data, forcing use of methods for safety.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
__balanceN/A100 (hidden)150 (hidden)150 (hidden)150 (hidden)
Key Moments - 3 Insights
Why can't we access __balance directly from outside the class?
Because __balance is a private variable (see step 4 in execution_table), Python blocks direct access to protect data.
How do we safely change the balance?
We use the deposit method (step 2) which updates the balance inside the class, ensuring controlled changes.
What happens if we try to access the private variable using name mangling?
It works (step 5), but it breaks encapsulation rules and should be avoided to keep data safe.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the balance after calling deposit(50)?
A150
B50
C100
DAttributeError
💡 Hint
Check step 2 in the execution_table where deposit updates the balance.
At which step does direct access to __balance cause an error?
AStep 2
BStep 4
CStep 5
DStep 3
💡 Hint
Look at step 4 in the execution_table where direct access is blocked.
If we remove the __ prefix from balance, what changes in the execution?
ADeposit method will stop working
Bget_balance will return error
CDirect access to balance will be allowed
DBalance will become read-only
💡 Hint
Removing __ means the variable is no longer private, so direct access is possible.
Concept Snapshot
Encapsulation hides data inside a class using private variables (like __balance).
Access and changes happen only through methods.
This protects data from accidental or unauthorized changes.
Use methods to safely interact with hidden data.
Direct access to private data causes errors or breaks rules.
Full Transcript
Encapsulation is a way to keep data safe inside a class by hiding it with private variables. In the example, the BankAccount class hides the balance using __balance. You can only change or see the balance by calling methods like deposit or get_balance. Trying to access __balance directly causes an error, which protects the data. This helps keep the data safe and controlled. Sometimes, you can access it using special tricks, but that breaks the safety rules. Always use methods to work with private data.

Practice

(1/5)
1. What is the main purpose of encapsulation in Python classes?
easy
A. To allow unlimited access to all variables
B. To hide internal data and protect it from outside access
C. To make the program run faster
D. To print data directly to the screen

Solution

  1. Step 1: Understand encapsulation concept

    Encapsulation means hiding data inside a class to protect it from outside changes.
  2. Step 2: Identify the main goal

    The goal is to keep data safe and control access through methods.
  3. Final Answer:

    To hide internal data and protect it from outside access -> Option B
  4. Quick Check:

    Encapsulation = Data protection [OK]
Hint: Encapsulation means hiding data inside classes [OK]
Common Mistakes:
  • Thinking encapsulation speeds up code
  • Believing encapsulation allows free access
  • Confusing encapsulation with printing data
2. Which of the following is the correct way to make a variable private in a Python class?
easy
A. variable
B. _variable
C. __variable
D. public_variable

Solution

  1. Step 1: Recall Python private variable syntax

    In Python, prefixing a variable with double underscore __ makes it private.
  2. Step 2: Compare options

    Only __variable uses double underscore, so it is private.
  3. Final Answer:

    __variable -> Option C
  4. Quick Check:

    Double underscore = private variable [OK]
Hint: Use double underscore to make variables private [OK]
Common Mistakes:
  • Using single underscore which is only a convention
  • Using no underscore which is public
  • Confusing variable names with public keywords
3. What will be the output of this code?
class Box:
    def __init__(self):
        self.__content = 'secret'
    def reveal(self):
        return self.__content

b = Box()
print(b.reveal())
print(b.__content)
medium
A. secret secret
B. AttributeError AttributeError
C. AttributeError secret
D. secret AttributeError

Solution

  1. Step 1: Understand private variable access

    The variable __content is private and cannot be accessed directly outside the class.
  2. Step 2: Check print statements

    Calling b.reveal() returns 'secret'. But b.__content causes AttributeError because it's private.
  3. Final Answer:

    secret AttributeError -> Option D
  4. Quick Check:

    Private variable accessed via method only [OK]
Hint: Private variables cause error if accessed directly [OK]
Common Mistakes:
  • Expecting direct access to private variables
  • Ignoring AttributeError on private access
  • Assuming private variables print normally
4. Find the error in this code related to encapsulation:
class Person:
    def __init__(self, name):
        self.__name = name

p = Person('Anna')
print(p.__name)
medium
A. AttributeError because __name is private
B. SyntaxError due to private variable
C. No error, prints 'Anna'
D. TypeError because __name is missing

Solution

  1. Step 1: Identify private variable usage

    The variable __name is private and cannot be accessed directly outside the class.
  2. Step 2: Analyze print statement

    Trying to print p.__name causes AttributeError because it is private.
  3. Final Answer:

    AttributeError because __name is private -> Option A
  4. Quick Check:

    Private variables cause AttributeError on direct access [OK]
Hint: Private variables cause AttributeError if accessed directly [OK]
Common Mistakes:
  • Thinking private variables print normally
  • Confusing syntax error with attribute error
  • Trying to access private variables without methods
5. You want to protect a bank account balance so it cannot be changed directly. Which encapsulation approach is best?
hard
A. Use a private variable for balance and provide methods to deposit and withdraw
B. Make balance a public variable and change it anywhere
C. Use global variables for balance
D. Print balance directly without storing it

Solution

  1. Step 1: Understand the need for protection

    Bank balance should not be changed directly to avoid mistakes or fraud.
  2. Step 2: Apply encapsulation best practice

    Use a private variable for balance and provide public methods to safely update it.
  3. Final Answer:

    Use a private variable for balance and provide methods to deposit and withdraw -> Option A
  4. Quick Check:

    Private variable + methods = safe data access [OK]
Hint: Use private variables with methods to control changes [OK]
Common Mistakes:
  • Making balance public and changing it anywhere
  • Using global variables which are unsafe
  • Not controlling how balance is updated