为什么即使使用“全局”也没有定义变量?

时间:2019-04-09 09:15:23

标签: python python-3.x global-variables

我正在尝试用Python做一个COOL编译器,但是当我尝试设置一个全局变量时,它说“ NameError:未定义名称'comm_reg'”。我首先定义了变量,然后将其用作全局变量,所以我不明白为什么它不起作用。

有什么想法吗?谢谢。

class CoolLexer(Lexer):

    comm_reg = False
    comm_line = False

    @_(r'[(][\*]')
    def COMMENT(self, t):
        global comm_reg
        comm_reg = True

    @_(r'[*][)]')
    def CLOSE_COMMENT(self, t):
        global comm_reg
        if comm_reg:
            comm_reg = False
        else:
            return t

    @_(r'[-][-].*')
    def ONE_LINE_COMMENT(self, t):
        global comm_line
        comm_line = True

    def salida(self, texto):
        list_strings = []
        for token in lexer.tokenize(texto):
            global comm_line
            global comm_reg
            if comm_reg:
                continue
            elif comm_line:
                comm_line = False
                continue
            result = f'#{token.lineno} {token.type} '

1 个答案:

答案 0 :(得分:1)

您似乎想要这样的东西:

class CoolLexer(Lexer):

    def __init__(self):
        self.comm_reg = False
        self.comm_line = False

    @_(r'[(][\*]')
    def COMMENT(self, t):
        self.comm_reg = True

    @_(r'[*][)]')
    def CLOSE_COMMENT(self, t):
        if self.comm_reg:
            self.comm_reg = False
        else:
            return t

    @_(r'[-][-].*')
    def ONE_LINE_COMMENT(self, t):
        self.comm_line = True

    def salida(self, texto):
        list_strings = []
        for token in self.tokenize(texto):
            if self.comm_reg:
                continue
            elif self.comm_line:
                self.comm_line = False
                continue
            result = f'#{token.lineno} {token.type} '
相关问题