在Python中,前缀为一个下划线表示不应在其类之外访问成员。这似乎是基于每个类别Java和C++。
但是,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。
答案 0 :(得分:10)
pylint不知道other
是哪种类型(它应该如何,你可以将A的实例与所有内容进行比较),因此警告。我认为没有办法解除警告。
您可以仅为该一行禁用警告,并在该行附加# pylint: disable=W0212
。
答案 1 :(得分:1)
克里斯蒂安·盖尔(Christian Geier)正确地解释了为什么会收到该错误以及如何将其禁用。
不过,我鼓励您考虑更改代码:pylint告诉您一些重要的信息。从示例代码来看,您似乎想使用A类的eq比较对象与A类的其他对象,但是您的示例无法保证调用者不会尝试A() == C()
。当您检查True
时返回Circle()._radius == Sphere._radius
可能会引起问题。
有关如何处理此问题的信息,请参见this stackoverflow thread。