Junior — Middle
Explain the mechanism and features of methods declared as protected in a class.
sobes.tech AI
Answer from AI
Python does not have strict access modifiers like some other languages (e.g., private, protected, public in C++ or Java). However, there is a convention that methods and attributes whose names start with a single underscore (_method) are considered protected. This means they are intended for use within the class and its subclasses, but not for external use.
Features:
- Protected methods do not prohibit external access; it is merely a convention.
- Subclasses can freely use and override such methods.
- Using a single underscore helps developers understand that the method is not meant for public API.
Example:
class Base:
def _protected_method(self):
print("This is a protected method")
class Derived(Base):
def use_protected(self):
self._protected_method() # permissible
obj = Derived()
obj.use_protected()
# External call is possible but not recommended:
obj._protected_method()
Thus, protected methods in Python are more of an agreement than a strict access control mechanism.