在python中用函数声明全局变量

2024-10-03 09:13:03 发布

您现在位置:Python中文网/ 问答频道 /正文

这段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函数那样运行,因为任何全局函数都需要以某种方式返回。在


Tags: 函数代码thatlocalfunctionjavascript全局variable
3条回答

我知道这可能是最糟糕的实现;),但我试图考虑其他可能性,这在某种程度上更接近问题中的javascript代码。在

安装文件:1 U_全局.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:使用_一些.py在

^{pr2}$

除非调用“use_global_functions()”,否则无法访问函数

  1. 您必须创建一个单独的文件,其中包含所需的函数 全球使用。在
  2. 在任何其他python文件中导入这个文件,您应该可以开始了。在

你想模仿确切的功能有什么特别的原因吗?如果没有,这就足够了。在

根据不要在真实代码中执行此操作的标准免责声明,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 ^{} statement

Docs for ^{} statement

但如果你真的这样做,那么几乎可以肯定有更好的方法来做你想做的事情。在

相关问题 更多 >