给定一个带有一些受保护成员和公共接口以修改它们的类,什么情况下通常被认为可以直接访问受保护成员?我有一些具体的例子:
编辑 - 在下面添加一个简单的示例:
- 单元测试
- 内部私有方法,如__add__或__cmp__访问其他受保护的属性
- 递归数据结构(例如,在链表中访问next._data)
编辑 - 在下面添加一个简单的示例:
class Complex:
def __init__(self, imaginary, base):
self._imaginary = imaginary
self._base = base
def __str__(self):
return "%fi + %f" % self._base, self._imaginary
def __add__(self, other):
return Complex(self._imaginary + other._imaginary, self._base + other._base)
Pycharm在如下位置标注other._imaginary和other._base:
访问了一个类的保护成员_imaginary