Search code examples
oopsubclassencapsulationprotected

How to access a parent class attribute without breaking data encapsulation?


In the 1994 book Design Patterns: Elements of Reusable Object-Oriented Software by the "Gang of Four", I noticed in the C++ code examples that all methods are either declared as public or protected (never as private) and that all attributes are declared as private (never as public or protected).

In the first case, I suppose that the authors used protected methods instead of private methods to allow implementation inheritance (subclasses can delegate to them).

In the second case, while I understand that avoiding public and protected attributes prevents breaking data encapsulation, how do you do without them if a subclass need access a parent class attribute?

For example, the following Python code would have raised an AttributeError at the get_salary() method call if the _age attribute was private instead of protected, that is to say if it was named __age:

class Person:

    def __init__(self, age):
        self._age = age  # protected attribute


class Employee(Person):

    def get_salary(self):
        return 5000 * self._age


Employee(32).get_salary()  # 160000

Solution

  • I have finally found out an obvious solution by myself: redeclaring the private attribute of the parent class in the subclass:

    class Person:
    
        def __init__(self, age):
            self.__age = age  # private attribute
    
    
    class Employee(Person):
    
        def __init__(self, age):
            self.__age = age  # private attribute
    
        def get_salary(self):
            return 5000 * self.__age
    
    
    Employee(32).get_salary()  # 160000