【发布时间】: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) 的警告。
【问题讨论】: