Junior — Middle
Do you believe that encapsulation implies restricting access to internal data of an object?
sobes.tech AI
Answer from AI
Yes, encapsulation involves restricting access to an object's internal data and methods to protect them from direct external interference. This allows controlling how data is modified and used, ensuring the integrity of the object's state.
In Python, encapsulation is implemented through conventions:
- Attributes with a single underscore
_attrare considered protected — not intended for direct external access. - Attributes with double underscores
__attrtrigger name mangling, making external access more difficult (private).
Example:
class MyClass:
def __init__(self):
self.__private_var = 42 # hidden attribute
def get_private_var(self):
return self.__private_var
obj = MyClass()
print(obj.get_private_var()) # 42
# print(obj.__private_var) # AttributeError
Thus, encapsulation helps hide internal implementation details and provides a controlled interface.