【问题标题】:Pylint W0212 protected-accessPylint W0212 受保护访问
【发布时间】:2016-02-29 14:05:27
【问题描述】:

在 Python 中,带有一个下划线的前缀表示不应在其类之外访问成员。这似乎是基于每个班级的,例如 JavaC++

但是,pylint 似乎在每个对象的基础上强制执行此约定。有没有办法在不诉诸#pylint: disable=protected-access 的情况下允许每个班级访问?

class A:
    def __init__(self):
        self._b = 5

    def __eq__(self, other):
        return self._b == other._b

结果:

pylint a.py
a.py:6: W0212(protected-access) Access to a protected member _b of a client class

Pylint 描述了消息here

【问题讨论】:

标签: python private-members pylint


【解决方案1】:

pylint 不知道 other 是哪种类型(应该怎么做,您可以将 A 的实例与所有内容进行比较),因此发出警告。我认为没有办法禁用警告。

您可以通过将# pylint: disable=W0212 附加到该行来仅禁用该行的警告。

【讨论】:

  • # pylint: disable=protected-access
【解决方案2】:

Christian Geier 对您收到错误的原因以及如何禁用它是正确的。

不过,我鼓励您考虑更改代码:pylint 告诉您一些重要的事情。从您的示例代码看来,您想使用 eq 将 A 类的对象与 A 类的其他对象进行比较,但您的示例不能保证调用者不会尝试 A() == C()。当您检查 Circle()._radius == Sphere._radius 时返回 True 似乎可能会导致问题。

请参阅this stackoverflow thread,了解如何处理此问题。

【讨论】:

    猜你喜欢
    • 2014-09-10
    • 1970-01-01
    • 2020-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-06
    • 2011-04-02
    • 2013-03-05
    相关资源
    最近更新 更多