【问题标题】:Pylint warning `W0212` with properties accessing a protected member: how to avoid?带有访问受保护成员的属性的 Pylint 警告“W0212”:如何避免?
【发布时间】:2014-09-10 02:02:34
【问题描述】:

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

例如

class C(object):

    def __init__(self):
        C.__a = 0

    a = property(lambda self: self.__a)

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

我不想全局禁用W0212,而且我对在本地(*)为每个此类属性定义反复禁用它不满意。

有没有已知的解决方法?

(*)如:

class C(object):

    def __init__(self):
        C.__a = 0

    a = property(lambda self: self.__a)  # pylint: disable=W0212

保证金说明

作为一个有趣的附注,我选择的答案为实际 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)

您将收到print(o.a().nonexistent)print(o.b.nonexistent) 的警告,但不会收到print(o.c.nonexistent) 的警告。

【问题讨论】:

    标签: python pylint


    【解决方案1】:

    在我看来,您可以使用装饰器,而 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
    

    因为这样 linter 可以轻松地将 a 识别为类上的方法。否则,您几乎会被列出的选项卡住。您可以全局或本地禁用警告,或者根本不禁用 - 据我所知,无法仅在特定上下文中禁用警告。

    【讨论】:

    • 我发现您的贡献具有附加价值。见原帖。多亏了你,我会根据你的建议从 Pylint 那里得到更多。
    猜你喜欢
    • 1970-01-01
    • 2016-07-23
    • 2016-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-06
    • 2017-02-22
    • 2018-01-18
    相关资源
    最近更新 更多