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

时间:2017-03-11 13:53:37

标签: python oop attributes protected

给定一个带有一些受保护成员的类和一个用于修改它们的公共接口,何时可以直接访问受保护成员?我有一些具体的例子:

  1. 单元测试
  2. 内部私有方法,例如__add__或__cmp__访问其他受保护的属性
  3. 递归数据结构(例如,访问链表中的next._data)
  4. 我不想公开这些属性,因为我不希望他们公开触及。我的语法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._imaginary other._base

      

    访问类的受保护成员_imaginary

1 个答案:

答案 0 :(得分:3)

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

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)
相关问题