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

Rav*_*ven 7 python oop attributes protected

给定一个具有一些受保护成员的类,并通过一个公共接口对其进行修改,通常什么时候可以直接访问受保护成员?我想到了一些具体的例子:

  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)
Run Code Online (Sandbox Code Playgroud)

Pycharm 使用以下内容突出显示other._imaginaryother._base

访问类的受保护成员_imaginary

Rav*_*ven 6

已解决 - 问题实际上与缺乏类型提示有关。以下现在有效:

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)
Run Code Online (Sandbox Code Playgroud)