python - NameError : name 'self' is not defined, 即使它是?

标签 python class oop

谁能帮我理解为什么这会给我一个错误?错误是“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/

相关文章:

python - 按字典值对字典列表进行排序

python - Numpy 向量化打乱数据类型(二)

python - 在不耗尽 RAM 的情况下使用 Concurrent Futures

c++ - 从子类调用非虚方法

javascript - 在另一个类中使用一个类

python - 使用 xpath 选择子文本节点

java - 构造函数中的 if 语句未按预期工作? java

oop - (如何) raku 做类同义词?

python - 设置对象实例变量的正确方法

javascript - 不可设置和不可写的属性仍然是可变的