Sobes.tech
Junior — Middle

What does the protected access modifier mean and how does it work in object-oriented programming?

sobes.tech AI

Answer from AI

The protected access modifier in object-oriented programming means that a class member (variable or method) is accessible within the class itself and in derived classes, but not accessible from other parts of the program.

In Python, there is no strict protected modifier, but by convention, a single underscore before the name indicates a protected member:

class Base:
    def __init__(self):
        self._protected_var = 42  # considered protected

class Derived(Base):
    def print_var(self):
        print(self._protected_var)  # access is allowed

obj = Derived()
obj.print_var()  # will output 42
# obj._protected_var  # technically accessible, but considered a violation of encapsulation

Thus, protected helps restrict access to internal class details, allowing them to be used in subclasses but hiding them from external code.