我很想知道是否需要在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()
答案 0 :(得分:1)
不,没有。如果要在该函数中设置全局变量的值,则需要在函数内使用global
。您不需要使用global
外部功能。
答案 1 :(得分:0)
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