Python 未定义全局名称
我正在尝试检查是否定义了全局文件Python 未定义全局名称,python,Python,我正在尝试检查是否定义了全局文件 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 有没有办法检查变量是否已声明?在运行检查之前是否必须初始化全局变量?
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
关键字:
import os, sys, logging...
my_logger = None
def init():
global my_logger
if my_logger is None:
print 'Logger needs to be initialized'
当需要引用全局变量时,而不是在定义全局变量时,可以使用
global
关键字:
import os, sys, logging...
my_logger = None
def init():
global my_logger
if my_logger is None:
print 'Logger needs to be initialized'
正如其他答案所述,在访问全局变量时需要全局关键字,而不是在声明时。需要注意的是,如果计划分配任何变量,只需将变量声明为
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'
正如其他答案所述,在访问全局变量时需要全局关键字,而不是在声明时。需要注意的是,如果计划分配任何变量,只需将变量声明为
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'
如果没有正确使用
global
关键字,请查阅相关文档
但是,作为一般规则,您可以测试全局变量的定义是否如下:
defined = 'my_logger' in globals()
if defined:
print('my_logger has not been defined')
如果没有正确使用
global
关键字,请查阅相关文档
但是,作为一般规则,您可以测试全局变量的定义是否如下:
defined = 'my_logger' in globals()
if defined:
print('my_logger has not been defined')
请注意,没有
全局my_logger
行,此代码同样可以正常工作,因为my_logger未被修改。实际上,您不需要它访问全局变量,只需要修改它们。请注意,没有全局my_logger
行,此代码同样可以正常工作,因为我的日志没有被修改。实际上,你不需要它来访问全局变量,只需要修改它们。如果你使用的是global
,你很可能做错了。如果你使用的是global
,你很可能做错了。非常感谢大家。非常感谢大家。