【问题标题】:NameError: name 'self' is not defined? [closed]NameError:名称'self'未定义? [关闭]
【发布时间】:2012-11-21 19:42:41
【问题描述】:

我目前正在从事 python 编程。

class A:
    def LoadPosition(self):
        FILE = open('a.txt', "r+")

        i = 0
        for node in self.nodes:
            line = FILE.readline()
            if i == 0:
                scaling_factor == float(line)
                i += 1
            else:
                tmpn, tmpx, tmpy, tmpa = line.split('\t')
                node.id = tmpn
                node.coordinate_x = float(tmpx)
                node.coordinate_y = float(tmpy)
                node.area = int(tmpa)
        FILE.close()

之前很好,但突然间,它显示了 NameError 消息。请帮帮我。

提前致谢。

【问题讨论】:

  • 您的原始代码中是否有相同的缩进?似乎这就是问题所在。您需要将函数中的所有代码向右缩进4 spaces
  • @RohitJain:他不能。那将是IndentationError: Unexpected unindent
  • @A.R.S.:看def …之后的那一行
  • 显示整个错误,包括回溯。没有它,你是在要求我们重新分析你的代码。
  • @SangChae 把它放在问题里。

标签: python nameerror


【解决方案1】:

您以奇怪的方式混合了空格和制表符,这可能会让 Python 感到困惑。这是我从编辑窗口复制并粘贴代码时得到的结果:

In [2]: for line in s.splitlines():
   ...:     print repr(line)
   ...:     
''
'    class A:'
'    \tdef LoadPosition(self):'
'\t        FILE = open(\'a.txt\', "r+")'
'    \t'
'\t\t    i = 0'
'    \t    for node in self.nodes:'
'    \t    \tline = FILE.readline()'
'    \t    \tif i == 0:'
'    \t    \t\tscaling_factor == float(line)'
'    \t    \t\ti += 1'
'    \t    \telse:'
"    \t    \t\ttmpn, tmpx, tmpy, tmpa = line.split('\t')"
'\t       \t     \tnode.id = tmpn'
'   \t\t         \tnode.coordinate_x = float(tmpx)'
'   \t\t         \tnode.coordinate_y = float(tmpy)'
'   \t\t     \t    node.area = int(tmpa)'
'\t\t    FILE.close()'

[请注意,如果有人从发布的问题而不是原始编辑窗口复制代码,这可能不会发生 - 至少有时它会被禁止看到我的原始选项卡 - 因此尝试您的代码的人可能没有任何问题。]

第 1 步:使用 python -tt yourfilenamehere.py 运行您的代码以确认这是一个选项卡错误。

第 2 步:切换到在任何地方使用四空格制表符。

【讨论】:

  • 原始代码很好,但是谢谢。
  • @SangChae:你是说原代码幸存下来了python -tt
  • 哦,我的错。你的评论是对的。这很有帮助!谢谢。
猜你喜欢
  • 1970-01-01
  • 2021-08-23
  • 2016-12-20
  • 2023-03-05
  • 2020-12-23
  • 2014-03-18
  • 2021-07-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多