Python 为什么即使我使用了";全球;?

Python 为什么即使我使用了";全球;?,python,python-3.x,global-variables,Python,Python 3.x,Global Variables,我试图用Python编写一个很酷的编译器,但当我尝试设置一个全局变量时,它会说“NameError:name'comm_reg'未定义”。我在一开始定义变量,然后将其用作全局变量,所以我不明白它为什么不起作用 有什么想法吗?多谢各位 class CoolLexer(Lexer): comm_reg = False comm_line = False @_(r'[(][\*]') def COMMENT(self, t): global comm

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

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

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

看起来您想要使用类的实例变量。您使用哪个库来定义Lexer?该库仅用于封装全局变量。使用
self
对象,而不是
global
:-)是的,它工作!!!非常感谢你。那么,全球和自我之间有什么区别呢?