【发布时间】:2017-08-01 20:10:32
【问题描述】:
给定一个具有一些受保护成员的类和一个用于修改它们的公共接口,通常何时可以直接访问受保护成员?我想到了一些具体的例子:
- 单元测试
- 内部私有方法,例如 __add__ 或 __cmp__ 访问其他受保护的属性
- 递归数据结构(例如访问链表中的 next._data)
我不想公开这些属性,因为我不希望它们被公开。我的语法 IDE 语法突出显示一直说我访问受保护成员时出错 - 谁在这里?
EDIT - 在下面添加一个简单的示例:
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 类
【问题讨论】:
-
你举的三个例子是有道理的。此外,在需要时(显然)在代码中访问它们是可以接受的。你能发布你的语法荧光笔告诉你的内容吗?我要求它是因为访问受保护的成员非常基本。
标签: python oop attributes protected