如何使局部变量(函数内部)全局

2024-03-29 14:30:16 发布

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

Possible Duplicate:
Using global variables in a function other than the one that created them

我使用函数,这样我的程序就不会一团糟,但我不知道如何将局部变量变成全局变量。


Tags: the函数inthatfunctionvariablesglobalone
3条回答

只需在任何函数外部声明变量:

globalValue = 1

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

如果需要从函数内部将赋值给全局,请使用global语句:

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

有两种方法可以实现相同的目的:

使用参数并返回(推荐)

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()`

如果需要访问函数的内部状态,那么最好使用类。通过使类实例成为可调用的函数,可以使其像函数一样工作,这是通过定义__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`

相关问题 更多 >