Python - 访问类的受保护成员_

17
给定一个带有一些受保护成员和公共接口以修改它们的类,什么情况下通常被认为可以直接访问受保护成员?我有一些具体的例子:
  1. 单元测试
  2. 内部私有方法,如__add__或__cmp__访问其他受保护的属性
  3. 递归数据结构(例如,在链表中访问next._data)
我不想将这些属性公开,因为我不希望它们被公开访问。我的语法IDE语法高亮显示一直在说我访问受保护成员是错误的 - 谁是正确的?
编辑 - 在下面添加一个简单的示例:
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._imaginaryother._base:

访问了一个类的保护成员_imaginary


你给出的三个例子是合理的。当需要时,在代码中访问它们也是可以接受的(显然)。你能发布一下你的语法高亮器告诉你什么吗?我之所以问这个问题,是因为保护成员被访问是非常基本的。 - nir0s
1个回答

7
解决了 - 问题实际上与缺乏类型提示有关。现在以下内容可以正常工作:
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):
        """
        :type other: Complex
        :rtype Complex:
        """
        return Complex(self._imaginary + other._imaginary, self._base + other._base)

在函数签名中写(self, other: Complex) -> Complex应该是可能的,但据我所知,使用这种语法无法引用当前类... - Andreas detests censorship
1
@Chris 这是为 Python 2.7 编写的,它没有类型注释,但我不认为它不能工作。 - Raven
@Chris FYI https://dev59.com/3lwX5IYBdhLWcg3wrA96 - Raven

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接