Junior — Middle
Is encapsulation a mechanism for restricting access to methods and data within a class?
sobes.tech AI
Answer from AI
Encapsulation is a principle of object-oriented programming that combines data (attributes) and methods that work with this data into a single class. It is often understood as a mechanism to restrict access to the internal data and methods of a class to protect them from direct external modification.
In Python, encapsulation is not strictly enforced but rather implemented through conventions:
- Attributes and methods with a single underscore (
_attr) are considered protected and are not intended for use outside the class and its subclasses. - Attributes and methods with double underscores (
__attr) invoke name mangling, which makes external access more difficult.
Example:
class MyClass:
def __init__(self):
self.public = 1
self._protected = 2
self.__private = 3
def get_private(self):
return self.__private
obj = MyClass()
print(obj.public) # 1
print(obj._protected) # 2 (not recommended for external use)
#print(obj.__private) # Error
print(obj.get_private()) # 3
Thus, encapsulation in Python is a mechanism for combining data and methods, as well as a means of restricting access to internal class elements. However, these restrictions are conditional and based on conventions rather than strict language rules.