gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 10:36:41 24 4
gpt4 key购买 nike

这段 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com