0
0
Pythonprogramming~20 mins

Purpose of encapsulation in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Encapsulation Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
Why do we use encapsulation in programming?

Encapsulation is a key idea in programming. What is its main purpose?

ATo make the program use more global variables
BTo make the program run faster by using less memory
CTo allow all parts of the program to change data freely
DTo hide internal details and protect data from outside access
Attempts:
2 left
💡 Hint

Think about keeping things safe inside a box.

Predict Output
intermediate
2:00remaining
Output of code using encapsulation

What will this Python code print?

Python
class Box:
    def __init__(self):
        self.__secret = 'hidden'
    def reveal(self):
        return self.__secret

b = Box()
print(b.reveal())
ANone
BAttributeError
Chidden
Dsecret
Attempts:
2 left
💡 Hint

Look at how the secret is accessed inside the class.

Predict Output
advanced
2:00remaining
What error does this code raise?

What happens when this code runs?

Python
class Safe:
    def __init__(self):
        self.__code = 1234

s = Safe()
print(s.__code)
AAttributeError
BNameError
CTypeError
D1234
Attempts:
2 left
💡 Hint

Private variables cannot be accessed directly outside the class.

🧠 Conceptual
advanced
2:00remaining
Which is NOT a benefit of encapsulation?

Encapsulation offers many benefits. Which one below is NOT a benefit?

AAllows direct access to all internal data
BImproves security by hiding data
CHelps maintain code by controlling data access
DPrevents accidental changes to data
Attempts:
2 left
💡 Hint

Think about what encapsulation restricts.

🚀 Application
expert
2:00remaining
How many items are in the dictionary after running this code?

Consider this Python class using encapsulation. How many items does the dictionary data have after running?

Python
class DataHolder:
    def __init__(self):
        self.__data = {"a": 1, "b": 2}
    def get_data(self):
        return self.__data

holder = DataHolder()
data = holder.get_data()
data["c"] = 3
print(len(holder.get_data()))
A2
B3
C1
D0
Attempts:
2 left
💡 Hint

Think about whether the dictionary is copied or referenced.