Python 如何使局部变量(在函数内)成为全局变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14051916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make a local variable (inside a function) global
提问by
Possible Duplicate:
Using global variables in a function other than the one that created them
可能的重复:
在函数中使用全局变量而不是创建它们的函数
I'm using functions so that my program won't be a mess but I don't know how to make a local variable into global.
我正在使用函数,这样我的程序就不会一团糟,但我不知道如何将局部变量变成全局变量。
采纳答案by Alex L
Here are two methods to achieve the same thing:
这里有两种方法可以实现相同的目的:
Using parameters and return (recommended)
使用参数和返回(推荐)
def other_function(parameter):
return parameter + 5
def main_function():
x = 10
print x
x = other_function(x)
print x
When you run main_function, you'll get the following output
运行时main_function,您将获得以下输出
>>> 10
>>> 15
Using globals (never do this)
使用全局变量(永远不要这样做)
x = 0 # The initial value of x, with global scope
def other_function():
global x
x = x + 5
def main_function():
print x # Just printing - no need to declare global yet
global x # So we can change the global x
x = 10
print x
other_function()
print x
Now you will get:
现在你会得到:
>>> 0 # Initial global value
>>> 10 # Now we've set it to 10 in `main_function()`
>>> 15 # Now we've added 5 in `other_function()`
回答by Greg Hewgill
Simply declare your variable outside any function:
只需在任何函数之外声明您的变量:
globalValue = 1
def f(x):
print(globalValue + x)
If you need to assignto the global from within the function, use the globalstatement:
如果您需要从函数内部分配给全局,请使用以下global语句:
def f(x):
global globalValue
print(globalValue + x)
globalValue += 1
回答by Arafangion
Using globals will also make your program a mess - I suggest you try very hard to avoid them. That said, "global" is a keyword in python, so you can designate a particular variable as a global, like so:
使用全局变量也会让你的程序变得一团糟——我建议你努力避免它们。也就是说,"global" 是 python 中的一个关键字,因此您可以将特定变量指定为全局变量,如下所示:
def foo():
global bar
bar = 32
I should mention that it is extremely rare for the 'global' keyword to be used, so I seriously suggest rethinking your design.
我应该提到的是,使用“global”关键字的情况极为罕见,因此我郑重建议您重新考虑您的设计。
回答by Matthew Trevor
If you need access to the internal states of a function, you're possibly better off using a class. You can make a class instance behave like a function by making it a callable, which is done by defining __call__:
如果您需要访问函数的内部状态,最好使用类。您可以通过将类实例设为可调用来使类实例表现得像一个函数,这是通过定义__call__:
class StatefulFunction( object ):
def __init__( self ):
self.public_value = 'foo'
def __call__( self ):
return self.public_value
>> f = StatefulFunction()
>> f()
`foo`
>> f.public_value = 'bar'
>> f()
`bar`
回答by Matthew Trevor
You could use module scope. Say you have a module called utils:
您可以使用模块范围。假设您有一个名为 的模块utils:
f_value = 'foo'
def f():
return f_value
f_valueis a module attribute that can be modified by any other module that imports it. As modules are singletons, any change to utilsfrom one module will be accessible to all other modules that have it imported:
f_value是一个模块属性,可以被导入它的任何其他模块修改。由于模块是单例,utils所有其他导入它的模块都可以访问一个模块的任何更改:
>> import utils
>> utils.f()
'foo'
>> utils.f_value = 'bar'
>> utils.f()
'bar'
Note that you can import the function by name:
请注意,您可以按名称导入函数:
>> import utils
>> from utils import f
>> utils.f_value = 'bar'
>> f()
'bar'
But not the attribute:
但不是属性:
>> from utils import f, f_value
>> f_value = 'bar'
>> f()
'foo'
This is because you're labeling the object referenced by the module attribute as f_valuein the local scope, but then rebinding it to the string bar, while the function fis still referring to the module attribute.
这是因为您将 module 属性引用的对象标记为f_value在本地范围内,然后将其重新绑定到 string bar,而该函数f仍然引用 module 属性。

