【发布时间】:2026-01-13 00:15:01
【问题描述】:
在“四人帮”于 1994 年出版的 Design Patterns: Elements of Reusable Object-Oriented Software 书中,我注意到在 C++ 代码示例中,所有方法 要么声明为 public,要么protected(从不作为private)并且所有属性都被声明为private(从不作为public或protected)。
在第一种情况下,我假设作者使用protected 方法而不是private 方法来允许实现继承(子类可以委托给它们)。
在第二种情况下,虽然我知道避免 public 和 protected 属性可以防止破坏数据封装,如果子类需要访问父类属性,如果没有它们,你怎么办?
例如,如果_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