我有以下代码:
class Class1(object):
"""Demo Class"""
def __init__(self):
self.name = None
self.lines = []
@classmethod
def from_log(cls, log):
"""Instantiate from log"""
cls = Class1()
cls.name = 'log'
for line in log.splitlines():
cls.lines.append(line) # <-- pylint message here
return cls
OBJ = Class1.from_log("line1\nline2")
print(OBJ.lines)
导致pylint抱怨:
E1101:Class 'Class1' has no 'lines' member
这里有什么问题?由于它抱怨cls.lines
,为什么不抱怨cls.name
?
我正在使用:
编辑:感谢user2357112我意识到我误解了cls的类型。 cls是Class1的类对象。我正在创建的是Class1的一个实例。那不一样。重用它会混淆pylint。正确的代码如下:
class Class1(object):
"""Demo Class"""
def __init__(self):
self.name = None
self.lines = []
@classmethod
def from_log(cls, log):
"""Instanciate from log-file"""
newobj = Class1() # <-- don't reuse cls. create a new variable.
newobj.name = 'log'
for line in log.splitlines():
newobj.lines.append(line)
return newobj
它甚至可以是:
newobj = cls()