Junior — Middle
What is the scope of a variable inside a class and how is it determined?
sobes.tech AI
Answer from AI
In Python, the protected modifier is implemented by convention — the name of the method or attribute starts with an underscore _. This indicates that the method or attribute is intended for internal use within the class and its subclasses, not for external use.
Unlike Java, Python does not enforce access restrictions; it is only a developer convention.
Example:
class Base:
def _protected_method(self):
print("This is a protected method")
class Derived(Base):
def access_protected(self):
self._protected_method() # correct
obj = Derived()
obj.access_protected()
# obj._protected_method() # technically possible, but not recommended
Thus, protected methods help indicate internal implementation details that are not meant for public API.