简体   繁体   English

为什么这个python代码有效?

[英]Why does this python code work?

I have written a simple python module, it has this code: 我写了一个简单的python模块,它有这个代码:

_log = logging.getLogger("mymodule")
_started = False

def set_log_level(level):
    _log.setLevel(level)
    if not _started:
        _hdlr = logging.FileHandler('mymodule.log')

When I call set_log_level() program fails because symbol _started is not found. 当我调用set_log_level()程序失败,因为找不到符号_started It is normal because global _started is missing in the method. 这是正常的,因为方法中缺少global _started But my question is: symbol _log has the same visibility as _started , so why does this symbol can be found? 但我的问题是:象征_log具有一样的知名度_started ,所以为什么这个符号可以找到?

I don't think your program fails for the reason you think. 我认为您的计划因您认为的原因而失败。 There's no need to use the global declaration within a function unless you actually modify that variable. 除非您实际修改该变量,否则无需在函数内使用global声明。 (Otherwise, you'd need to use global for every access of something in that namespace, even calling other functions.) (否则,您需要对该名称空间中的某项内容的每次访问都使用global,甚至调用其他函数。)

I'm not sure what actually happens when you run your program - perhaps you could provide a traceback or description of the problem. 我不确定在运行程序时实际发生了什么 - 也许你可以提供追溯或问题的描述。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM