Skip to main content
 首页 » 编程设计

python之未定义全局名称

2025年05月04日13kevingrace

我正在尝试检查是否定义了全局文件。

import os, sys, logging... 
 
global my_logger 
 
def init(): 
  if my_logger is None: 
     print 'Logger needs to be initialized' 

但是,当我运行它时,出现错误:

NameError: global name 'my_logger' is not defined 

有没有办法检查变量是否已声明?在运行检查之前是否必须初始化全局变量?

请您参考如下方法:

正如其他答案所述,在访问全局变量时需要 global 关键字,而不是在声明时。应该注意的是,如果您打算为其分配任何内容,则只需将变量声明为 global - 您可以从更高范围读取变量,而无需使用 global 关键字:

my_logger = None 
 
def init_logger(): 
    #needs to use global because we assign to the variable 
    global my_logger 
    my_logger = MyLogger() 
 
def someOtherFunction(): 
    #no need to use global as we only access the logger 
    if my_logger: 
        my_logger.info("i can has logger") 
    else: 
        print 'logger not initialized'