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

2024-04-25 23:28:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用Python编写一个很酷的编译器,但是当我试图设置一个全局变量时,它会说“NameError:name'comm\u 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} '

Tags: selftokenfalsetrueifdeflinecomment
1条回答
网友
1楼 · 发布于 2024-04-25 23:28:59

看起来你想要这样的东西:

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} '

相关问题 更多 >