0

为什么我收到下面给出的错误:

lhs_production = self.lhs()  

名称错误:global name 'self' is not defined

下面是我写的代码:

class Grammar:
   def lhs(self):
      arrow_position = line.find('->')
      if arrow_position == -1:
         raise ValueError, 'No arrow position %s is found in %s' % (arrow_position, self.line)

      lhs_g = self.line[0:arrow_position].strip(' ')
      print "The Lhs for the line is: ", lhs_g

      check_space = re.search("\s", lhs, re.M)
      if check_space:
         raise ValueError, 'There is still some space in the lhs of the line'

      return self.lhs_g



def parse_line(line):
   if len(line) == 0:
      raise ValueError, 'No Line is found %s' % (line)
   lhs_production = self.lhs()
   rhs_predicates_production = rhs_predicates()
   pattern_list_production = pattern_list()
   return(lhs_production, rhs_predicates(), patterns())
4

3 回答 3

2

因为self未在该函数的范围内定义:)。您的缩进已关闭,您可能打算将其设为一个方法(因此所有行都缩进),然后self作为参数添加,在这种情况下,实例将采用 name self

其他一些需要注意的事情,只是通过:

  • 您应该使用if "->" in line:而不是.find()检查它是否为-1. 为此,您的第一个函数似乎有一个NameError, 因为line它的第一行没有定义,所以不确定您的意思。

  • 你应该实例化异常,而不是让 raise 为你做它(所以,raise ValueError("some stuff")

  • 您可以使用if not line它来检查它是否为空行。

  • return是一个语句,而不是一个函数,所以这样写有点混乱。return lhs_production, bla, bla如果您愿意,只要那里有空间,只需使用或放置括号即可。

干杯:)。

于 2012-07-24T21:48:36.840 回答
0

self 不是全局变量。它被传递给类方法。parse_line 函数是全局范围函数,而不是类方法。因此,self 不存在于该函数的范围内。

任何使用 self 的方法都需要将 self 作为参数。

于 2012-07-24T21:48:52.080 回答
0

在这种情况下没有自我,除非你的缩进是错误的。当超出对象的范围时,您需要引用对象的实例来调用方法。 self无论如何,它实际上只是一个标签;它只有约定俗成的特殊含义。你需要一个grammar=Grammar()在那里的某个地方。

于 2012-07-24T21:48:55.747 回答