Python - 如何使局部变量(在函数内)全局化

时间:2012-12-27 08:56:00

标签: python function global-variables local

  

可能重复:
  Using global variables in a function other than the one that created them

我正在使用函数,以便我的程序不会乱七八糟,但我不知道如何将局部变量设置为全局。

5 个答案:

答案 0 :(得分:27)

以下两种方法可以达到同样的效果:

使用参数并返回(推荐)

def other_function(parameter):
    return parameter + 5

def main_function():
    x = 10
    print x    
    x = other_function(x)
    print x

当您运行main_function时,您将获得以下输出

>>> 10
>>> 15

使用全局变量(从不这样做)

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

现在你会得到:

>>> 0    # Initial global value
>>> 10   # Now we've set it to 10 in `main_function()`
>>> 15   # Now we've added 5 in `other_function()`

答案 1 :(得分:11)

只需在任何函数之外声明您的变量:

globalValue = 1

def f(x):
    print(globalValue + x)

如果您需要从函数中分配到全局,请使用global语句:

def f(x):
    global globalValue
    print(globalValue + x)
    globalValue += 1

答案 2 :(得分:9)

如果您需要访问函数的内部状态,那么最好使用类。您可以通过将类实例设置为可调用来使类实例的行为类似于函数,这可以通过定义__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`

答案 3 :(得分:6)

使用全局变量也会让你的程序变得一团糟 - 我建议你尽量避免它们。也就是说,“global”是python中的关键字,因此您可以将特定变量指定为全局变量,如下所示:

def foo():
    global bar
    bar = 32

我应该提一下,'全球'关键字的使用极为罕见,所以我认真建议重新考虑你的设计。

答案 4 :(得分:4)

您可以使用模块范围。假设您有一个名为utils的模块:

f_value = 'foo'

def f():
    return f_value

f_value是一个模块属性,可以由导入它的任何其他模块修改。由于模块是单例,因此从一个模块对utils的任何更改都可以被导入的所有其他模块访问:

>> import utils
>> utils.f()
'foo'
>> utils.f_value = 'bar'
>> utils.f()
'bar'

请注意,您可以按名称导入该功能:

>> import utils
>> from utils import f
>> utils.f_value = 'bar'
>> f()
'bar'

但不是属性:

>> from utils import f, f_value
>> f_value = 'bar'
>> f()
'foo'

这是因为你在本地范围内将模块属性引用的对象标记为f_value,然后将其重新绑定到字符串bar,而函数f是仍然指的是模块属性。