1
我写了一个简单的Python模块,它有这个代码:为什么这个Python代码工作?
_log = logging.getLogger("mymodule")
_started = False
def set_log_level(level):
_log.setLevel(level)
if not _started:
_hdlr = logging.FileHandler('mymodule.log')
当我打电话,因为符号_started
没有找到set_log_level()
程序失败。这是正常的,因为方法中缺少global _started
。但我的问题是:符号_log
与_started
具有相同的可见性,那么为什么可以找到这个符号?
如果我在Python 2.7.1下运行这个,我没有错误。我添加了一行'set_log_level(3)'。 –
它不应该失败。那是所有代码吗? – delnan
是你的整个代码?你在实际运行的代码中是否有像'_started = True'这样的东西?在Python函数中存在赋值将会影响全局,即使赋值在第一次使用后出现*。 –