谁能帮我理解为什么这会给我一个错误?错误是“NameError:未定义名称'self'”。我的代码中有一个类似的类,它工作正常吗?
我正在使用“xlrd”,team 是对 workbook.sheet_by_name 的引用。
class Rollout:
def __init__(self, team, name):
self.team = team
self.name = name
self.jobs = {}
self.start_row = 1
self.last_row = self.team.nrows
for i in range(self.start_row,self.last_row):
try:
self.jobs[i-1] = [str(self.team.cell_value(i,0)).upper(), \
str(self.team.cell_value(i,1)).upper(), \
str(self.team.cell_value(i,2)).upper(), \
str(self.team.cell_value(i,3)).upper(), \
str(xlrd.xldate_as_tuple(self.team.cell_value(i,4),0)[3]), \
str(self.team.cell_value(i,5)).upper(), \
str(self.team.cell_value(i,6)).upper()]
except ValueError:
print "It look's like one of your 'time' cells is incorrect!"
self.jobs[i-1] = [str(self.team.cell_value(i,0)).upper(), \
str(self.team.cell_value(i,1)).upper(), \
str(self.team.cell_value(i,2)).upper(), \
str(self.team.cell_value(i,3)).upper(), \
"missing", \
str(self.team.cell_value(i,5)).upper(), \
str(self.team.cell_value(i,6)).upper()]
最佳答案
for
循环缩进不正确,导致它在该方法的范围之外,但在类的范围内。这反过来意味着 self
未定义。
Python 确实在类的范围内解释该循环代码,但没有对象的实例。格式错误的代码示例:
class Simple(object):
def __init__(self, a):
self.a = a
print("Here we go!")
for i in xrange(self.a):
print(i)
回溯
$ python simple.py
Here we go!
Traceback (most recent call last):
File "simple.py", line 4, in <module>
class Simple(object):
File "simple.py", line 9, in Simple
for i in xrange(self.a):
NameError: name 'self' is not defined
关于python - NameError : name 'self' is not defined, 即使它是?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20982780/