我很想知道是否需要在 Python 中的顶级声明/赋值中使用关键字global
(例如下面第一行代码的关键字(。
fn_2()
和fn_4()
在下面的代码中更改相应的变量具有相同的效果。
global factor_1
factor_1 = None
factor_2 = None
def main():
print('factor_1 = {}, factor_2 = {}'.format(factor_1, factor_2))
fn_1()
print('factor_1 = {}, factor_2 = {}'.format(factor_1, factor_2))
fn_2()
print('factor_1 = {}, factor_2 = {}'.format(factor_1, factor_2))
fn_3()
print('factor_1 = {}, factor_2 = {}'.format(factor_1, factor_2))
fn_4()
print('factor_1 = {}, factor_2 = {}'.format(factor_1, factor_2))
def fn_1():
factor_1 = 10
def fn_2():
global factor_1
factor_1 = 20
def fn_3():
factor_2 = 30
def fn_4():
global factor_2
factor_2 = 40
if __name__ == '__main__':
main()
不,没有。 如果要在函数中设置全局变量的值,则需要在该函数中使用global
。 无需使用global
外部函数。
global
允许您使用函数范围之外的变量,因此必须在函数内部使用它:
def fn_1():
# this is declaring a local variable factor_1
factor_1 = 10
def fn_2():
# this is changing the value of the global variable factor_1
global factor_1
factor_1 = 20
def fn_3():
# this is declaring a local variable factor_2
factor_2 = 30
def fn_4():
# this is changing the value of the global variable factor_2
global factor_2
factor_2 = 40