Pylint警告`W0212`,其属性访问受保护成员:如何避免?

Hib*_*u57 2 python pylint

Pylint警告可疑访问对象的受保护成员.它知道当访问来自对象时如何不警告,但是当访问来自对象的属性时,不知道如何不警告.

防爆.

class C(object):

    def __init__(self):
        C.__a = 0

    a = property(lambda self: self.__a)
Run Code Online (Sandbox Code Playgroud)

Pylint告诉" W0212(protected-access):访问__a客户端类的受保护成员"

我不想全局禁用W0212,我不满意在本地(*)为每个这样的属性定义重复禁用它.

有没有一种已知的解决方法?

(*)如:

class C(object):

    def __init__(self):
        C.__a = 0

    a = property(lambda self: self.__a)  # pylint: disable=W0212
Run Code Online (Sandbox Code Playgroud)

保证金说明

作为一个有趣的旁注,我选择的答案提供了实际Pylint的额外好处(可能在未来的版本中有所改变,我无法分辨):它保留了Pylint检查不存在的成员的能力,因为此测试显示:

class C1(object):

    member = 0


class C2(object):

    def __init__(self):
        self.__a = C1()

    def a(self):
        return self.__a

    @property
    def b(self):
        return self.__a

    c = property(lambda self: self.__a)


def test_member():

    o = C2()

    print(o.a().member)
    print(o.b.member)
    print(o.c.member)


def test_nonexistent():

    o = C2()

    print(o.a().nonexistent)
    print(o.b.nonexistent)
    print(o.c.nonexistent)
Run Code Online (Sandbox Code Playgroud)

你会得到警告print(o.a().nonexistent),print(o.b.nonexistent)但不是print(o.c.nonexistent).

mgi*_*son 5

在我看来,你可以使用装饰器,而且linter可能不会抱怨:

class C(object):

    def __init__(self):
        self.__a = 0

    @property
    def a(self):
        return self.__a

    # You can use the decorator to create setters too...
    @a.setter
    def a(self, value):
        self.__a = value
Run Code Online (Sandbox Code Playgroud)

因为那时linter很容易识别a出类中的方法.否则,你几乎坚持你列出的选项.您可以全局或本地禁用警告或根本不禁用警告 - 据我所知,仅在特定上下文中无法禁用警告.