这段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那样运行,因为任何全局都需要以某种方式返回。
答案 0 :(得分:1)
根据的标准免责声明不要在实际代码中执行此操作,您的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
但是,如果你真的这样做,那么几乎可以肯定的是,做你想做的事情要好得多。
答案 1 :(得分:0)
您是否有特定原因需要模仿确切的功能?如果不是这样就足够了。
答案 2 :(得分:0)
我知道这是最糟糕的实现;),但我试图接受其他可能性,这与问题中的javascript代码更接近。
文件1:setup_some_globals.py
num = 666
def g_alert_number():
global num
print num
def g_increase_number():
global num
num += 1
def g_set_number(x):
global num
num = x
变量num具有定义它的模块的范围。
文件2:use_some.py
def use_global_functions():
from setup_some_globals import g_alert_number, g_increase_number, g_set_number
global g_alert_number
g_alert_number = g_alert_number
global g_increase_number
g_increase_number = g_increase_number
global g_set_number
g_set_number = g_set_number
use_global_functions()
g_alert_number()
g_increase_number()
g_alert_number()
g_set_number(99)
g_alert_number()
您无法访问这些功能,除非您致电' use_global_functions()'