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

Posted

技术标签:

【中文标题】Python - 访问类的受保护成员_【英文标题】:Python - Access to a protected member _ of a class 【发布时间】: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._imaginaryother._base 如下:

访问受保护的成员 _imaginary 类

【问题讨论】:

你举的三个例子是有道理的。此外,在需要时(显然)在代码中访问它们是可以接受的。你能发布你的语法荧光笔告诉你的内容吗?我要求它是因为访问受保护的成员非常基本。 【参考方案1】:

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

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,但遗憾的是,据我所知,无法使用该语法引用当前类... @Chris 这是为没有类型注释的 python 2.7 编写的,但我不明白为什么它不应该工作 @Chris FYI ***.com/questions/33533148/…

以上是关于Python - 访问类的受保护成员_的主要内容,如果未能解决你的问题,请参考以下文章

静态成员函数无法访问类的受保护成员

从主访问类的受保护成员

在父类的子类中访问静态类的受保护成员

Java中的间接子类无法访问的超类中的受保护成员

我无法访问我的基类的受保护成员

访问另一个子类中基类的受保护成员