javascript - 在Python中使用函数声明全局变量

标签 javascript python global-variables

这段 JavaScript 代码运行良好。我的问题不在于修复代码本身,而在于如何在 Python 中模仿它。

function setupSomeGlobals() {
    // Local variable that ends up within closure
    var num = 666;
    // Store some references to functions as global variables
    gAlertNumber = function() { alert(num); }
    gIncreaseNumber = function() { num++; }
    gSetNumber = function(x) { num = x; }
}

当调用setupSomeGlobals()时,它会声明要全局使用的新函数。这可以在Python中以某种方式模仿吗?我不知道怎么办。 Python 函数似乎并不像 JavaScript 函数那样运行,因为任何全局的东西都需要以某种方式返回。

最佳答案

根据不要在实际代码中执行此操作的标准免责声明,您的 Javascript 的 Python (3) 翻译将如下所示:

def setup_some_globals():
    # Local variable
    num = 666

    # You have to explicitly declare variables to be global, 
    # otherwise they are local.
    global alert_number, increase_number, set_number

    def alert_number():
        # You can read a variable from an enclosing scope 
        # without doing anything special
        print(num)

    def increase_number():
        # But if you want to assign to it, you need to be explicit about 
        # it. `nonlocal` means "in an enclosing scope, but not 
        # global".
        nonlocal num
        num += 1

    def set_number(x):
        # Same as above
        nonlocal num
        num = x

# Usage:
>>> setup_some_globals()
>>> set_number(3)
>>> increase_number()
>>> alert_number()
4

Docs for nonlocal statement

Docs for global statement

但如果您确实这样做,那么几乎肯定有更好的方法来完成您想做的事情。

关于javascript - 在Python中使用函数声明全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28958975/

相关文章:

python - Perl 和 Python 在预声明函数方面的区别

c++ - 我们可以将全局静态变量视为全局变量吗

c - "cnt += num % 2;"和 "if (num % 2)++cnt;"之间的区别

javascript - 添加链接点击时弹出的文本

javascript - 读取图像像素

javascript - Ipad 滚动到达底部条件未满足

python - 了解变量类型、名称和赋值

python - 按 pandas 中的操作分组

c - 我们不能在全局范围内编写任何赋值语句,为什么?

javascript - 我制作了一些投票按钮(想想 reddit/digg/等)但是它们在 IE8 以下不起作用