Junior — Middle
Как отличить уровни доступа private, protected и public в объектно-ориентированном программировании, и чем они отличаются друг от друга?
sobes.tech AI
Answer from AI
In object-oriented programming, access levels determine which parts of the code can access certain class members (variables and methods):
- private — access is allowed only within the class itself. Members with this access level are not accessible from outside and in subclasses.
- protected — access is allowed within the class and its subclasses (inheritants). In Python, this is implemented by convention with a single underscore
_, although there is no strict protection. - public — access is allowed from everywhere, with no restrictions.
Python does not have strict encapsulation, but there are conventions:
- Name without underscores — public.
- Name with a single underscore (
_var) — protected (recommended not to use outside the class and its inheritors). - Name with double underscores (
__var) — private, with a name mangling mechanism to make external access more difficult.
Example:
class Example:
def __init__(self):
self.public_var = 1
self._protected_var = 2
self.__private_var = 3
def get_private(self):
return self.__private_var
obj = Example()
print(obj.public_var) # Accessible
print(obj._protected_var) # Accessible, but not recommended
# print(obj.__private_var) # Error
print(obj.get_private()) # Access through class method