如何在pycharm方法中抑制警告“访问受保护的成员”?

Gul*_*zar 10 python encapsulation pycharm

我有一些课

class A(object):
    def __init__(self, data):
        self._data = data
    def _equals(self, other):
        return self._data == other._data
Run Code Online (Sandbox Code Playgroud)

Pycharm 不喜欢我访问other._data它,因为它是私有的。

“访问受保护的成员”

这对我来说没有意义,因为访问是从班级内部进行的。

如何抑制此警告或编写正确的代码?

Pol*_*olv 11

如果你真的需要它,就像namedlist._asdict(),答案是我能得到PyCharm抑制对单行特定的警告?

class A(object):
    def __init__(self, data):
        self._data = data
    def _equals(self, other):
        # noinspection PyProtectedMember
        return self._data == other._data
Run Code Online (Sandbox Code Playgroud)


Gul*_*zar 4

Python 3.5+ 答案(引入了类型提示):

from __future__ import annotations


class A(object):
    def __init__(self, data):
        self._data = data

    def _equals(self, other: A):
        return self._data == other._data
Run Code Online (Sandbox Code Playgroud)

按照 @Giacomo Alzetta 的建议使用类型提示,并允许使用from __future__ import annotations.

无需再破解 PyCharm 或编写难看的注释。


正如 @jonrsharpe 所指出的,python 2 还支持通过文档字符串进行类型提示。
我不会在这里发布这个,因为我支持 Python 2,失去了支持。