简体   繁体   English

将局部变量的范围扩展为全局变量

[英]Extend the scope of a local variable into a global variable

In python we can declare a global variable which will be accessible by other functions. 在python中,我们可以声明一个全局变量,其他函数可以访问该变量。

my_global_var = 2

# foo can only access the variable for reading
def foo():
    print(my_global_var)

# bar can also write into the global variable
def bar():
    global my_global_var
    print(my_global_var)

This works, however suppose that I don't want to create the global variable outside foo and bar , but instead I want foo to create a local variable and extend the scope of this variable to bar (and any other function) without passing it as a parameter. 这可行,但是假设我不想在foobar之外创建全局变量,而是想让foo创建局部变量并将此变量的范围扩展到bar(以及任何其他函数)而无需将其传递为参数。

Something like 就像是

def foo():
    # the scope of this variable is only foo. Can I make it global?
    my_global_var = 4  

# bar wants to be able to access (and maybe modify) the variable created by foo
def bar():
    global my_global_var
    print(my_global_var)

PD: For the comments I think my question is not understood. PD:对于评论,我认为我的问题不明白。

It is clearly not a duplicate of that other question, since I know how to use global variables (the first example in the question uses them). 因为我知道如何使用全局变量(问题中的第一个示例使用它们),所以它显然不是另一个问题的重复项。

And I'm also not asking for suggestions about passing the variables as parameters or not using global variables. 而且我也没有要求有关将变量作为参数传递或不使用全局变量的建议。

My question is very specific. 我的问题很具体。 Can I extend the scope of a local variable into a global variable? 我可以将局部变量的范围扩展为全局变量吗?

It's either yes, it can be done this way or No, this cannot be done. 是的,可以通过这种方式完成,或者是的,无法完成。 And if the answer is yes I would like to know how can be done. 如果答案是肯定的,我想知道如何做。

There are any number of ways to work around this and sort of kind of emulate it, but really… No, there is no way to do exactly this . 有很多方法可以解决此问题并进行某种模拟,但是实际上……不,没有办法做到这一点

Scopes also define lifetimes. 范围还定义了生命周期。 A variable within a function scope can only exist while the function is running. 函数范围内的变量只能在函数运行时存在。 As soon as the function is done and its scope is destroyed, the variable ceases to exist. 一旦函数完成并且其作用域被破坏,变量就不再存在。 If you want the variable to continue to exist, it must live in a scope which also continues to exist. 如果希望变量继续存在,则它必须存在于也继续存在的范围内。 You could nest both functions inside another function to get that effect to some degree, but most likely you'll want to use the global scope for this, which always continues to exist. 您可以将两个函数嵌套在另一个函数中,以在某种程度上获得该效果,但是很可能您想为此使用全局范围,该范围始终存在。

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

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