Encapsulation is a key idea in programming. What is its main purpose?
Think about keeping things safe inside a box.
Encapsulation helps keep data safe by hiding it inside objects. This prevents outside code from changing it directly, which can cause errors.
What will this Python code print?
class Box: def __init__(self): self.__secret = 'hidden' def reveal(self): return self.__secret b = Box() print(b.reveal())
Look at how the secret is accessed inside the class.
The variable __secret is private but can be accessed inside the class method reveal(). So printing b.reveal() shows 'hidden'.
What happens when this code runs?
class Safe: def __init__(self): self.__code = 1234 s = Safe() print(s.__code)
Private variables cannot be accessed directly outside the class.
The variable __code is private. Trying to access s.__code from outside causes an AttributeError.
Encapsulation offers many benefits. Which one below is NOT a benefit?
Think about what encapsulation restricts.
Encapsulation restricts direct access to internal data. Allowing direct access is the opposite of encapsulation.
Consider this Python class using encapsulation. How many items does the dictionary data have after running?
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()))
Think about whether the dictionary is copied or referenced.
The method get_data returns the original dictionary reference. Adding "c":3 changes the original dictionary, so length is 3.