【问题标题】:How to access a parent class attribute without breaking data encapsulation?如何在不破坏数据封装的情况下访问父类属性?
【发布时间】:2026-01-13 00:15:01
【问题描述】:

在“四人帮”于 1994 年出版的 Design Patterns: Elements of Reusable Object-Oriented Software 书中,我注意到在 C++ 代码示例中,所有方法 要么声明为 public,要么protected(从不作为private)并且所有属性都被声明为private(从不作为publicprotected)。

在第一种情况下,我假设作者使用protected 方法而不是private 方法来允许实现继承(子类可以委托给它们)。

在第二种情况下,虽然我知道避免 publicprotected 属性可以防止破坏数据封装,如果子类需要访问父类属性,如果没有它们,你怎么办?

例如,如果_age 属性是private 而不是protected,则以下Python 代码将在get_salary() 方法调用中引发AttributeError,也就是说,如果它被命名为@987654337 @:

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

【问题讨论】:

    标签: oop subclass encapsulation protected


    【解决方案1】:

    我自己终于找到了一个明显的解决办法:在子类中重新声明父类的private属性:

    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
    

    【讨论】:

      最近更新 更多