Bird
Raised Fist0
Pythonprogramming~10 mins

Purpose of encapsulation in Python - Interactive Code Practice

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
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a class with a private attribute.

Python
class Person:
    def __init__(self, name):
        self.[1]name = name
Drag options to blanks, or click blank then click option'
A_
Bpublic_
C__
Dprivate_
Attempts:
3 left
💡 Hint
Common Mistakes
Using a single underscore instead of double underscores.
Using 'public_' or 'private_' as prefixes which are not valid in Python.
2fill in blank
medium

Complete the method to access the private attribute safely.

Python
class Person:
    def __init__(self, name):
        self.__name = name
    def get_name(self):
        return self.[1]name
Drag options to blanks, or click blank then click option'
A__
B_Person__
C_
Dpublic_
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to access __name directly without name mangling.
Using single underscore instead of name mangling.
3fill in blank
hard

Fix the error in the setter method to update the private attribute.

Python
class Person:
    def __init__(self, name):
        self.__name = name
    def set_name(self, name):
        self.[1]name = name
Drag options to blanks, or click blank then click option'
A__name
B_name
Cname
Dself.name
Attempts:
3 left
💡 Hint
Common Mistakes
Using a public attribute name instead of the private one.
Using single underscore or no underscore.
4fill in blank
hard

Fill both blanks to create a dictionary comprehension that stores private attribute lengths for names longer than 3.

Python
class Person:
    def __init__(self, name):
        self.__name = name

names = [Person('Anna'), Person('Bob'), Person('Catherine')]
lengths = {person.[1]name: len(person.[2]name) for person in names if len(person._Person__name) > 3}
Drag options to blanks, or click blank then click option'
A_Person__
B__
Cname
Dself
Attempts:
3 left
💡 Hint
Common Mistakes
Using __name or name directly outside the class.
Using single underscore or self which are invalid here.
5fill in blank
hard

Fill all three blanks to create a method that safely updates the private attribute only if the new name is longer than 2 characters.

Python
class Person:
    def __init__(self, name):
        self.__name = name
    def update_name(self, new_name):
        if len(new_name) > [1]:
            self.[2]name = new_name
            return True
        else:
            return [3]
Drag options to blanks, or click blank then click option'
A3
B__
CFalse
D2
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong length number in the condition.
Using single underscore or no underscore for private attribute.
Returning True instead of False when condition fails.

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