32 python function global-variables local
可能重复:
在创建它们的函数之外的函数中使用全局变量
我正在使用函数,以便我的程序不会乱七八糟,但我不知道如何将局部变量设置为全局.
Ale*_*x L 29
以下两种方法可以实现相同的目标:
使用参数和返回(推荐)
def other_function(parameter):
return parameter + 5
def main_function():
x = 10
print x
x = other_function(x)
print x
Run Code Online (Sandbox Code Playgroud)
运行时main_function,您将获得以下输出
>>> 10
>>> 15
Run Code Online (Sandbox Code Playgroud)
使用全局变量(从不这样做)
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
Run Code Online (Sandbox Code Playgroud)
现在你会得到:
>>> 0 # Initial global value
>>> 10 # Now we've set it to 10 in `main_function()`
>>> 15 # Now we've added 5 in `other_function()`
Run Code Online (Sandbox Code Playgroud)
Gre*_*ill 14
只需在任何函数之外声明您的变量:
globalValue = 1
def f(x):
print(globalValue + x)
Run Code Online (Sandbox Code Playgroud)
如果需要从函数中分配全局,请使用以下global语句:
def f(x):
global globalValue
print(globalValue + x)
globalValue += 1
Run Code Online (Sandbox Code Playgroud)
Mat*_*vor 10
如果您需要访问函数的内部状态,那么最好使用类.您可以通过将类实例设置为可调用来使类实例像函数一样,这可以通过定义__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`
Run Code Online (Sandbox Code Playgroud)
使用全局变量也会使你的程序变得混乱 - 我建议你尽量避免它们.也就是说,"global"是python中的关键字,因此您可以将特定变量指定为全局变量,如下所示:
def foo():
global bar
bar = 32
Run Code Online (Sandbox Code Playgroud)
我应该提一下,'全球'关键字的使用极为罕见,所以我认真建议重新考虑你的设计.
您可以使用模块作用域。假设您有一个名为的模块utils:
f_value = 'foo'
def f():
return f_value
Run Code Online (Sandbox Code Playgroud)
f_value是模块属性,导入该模块的任何其他模块均可对其进行修改。由于模块是单例,utils因此导入了该模块的所有其他模块都可以访问从一个模块进行的任何更改:
>> import utils
>> utils.f()
'foo'
>> utils.f_value = 'bar'
>> utils.f()
'bar'
Run Code Online (Sandbox Code Playgroud)
请注意,您可以按名称导入函数:
>> import utils
>> from utils import f
>> utils.f_value = 'bar'
>> f()
'bar'
Run Code Online (Sandbox Code Playgroud)
但不是属性:
>> from utils import f, f_value
>> f_value = 'bar'
>> f()
'foo'
Run Code Online (Sandbox Code Playgroud)
这是因为要像f_value在本地作用域中那样标记模块属性所引用的对象,然后将其重新绑定到字符串bar,而函数f仍在引用模块属性。