首页 > 文章列表 > python变量声明为全局变量的两种方法

python变量声明为全局变量的两种方法

python变量
367 2022-08-07

1、在函数内部分配变量并使用global line。

def declare_a_global_variable():
    global global_variable_1
    global_variable_1 = 1
 
# Note to use the function to global variables
declare_a_global_variable()

2、在函数外赋值。如果想在另一个函数中更改global line,update_variables()应该在分配变量之前使用global。

global_variable_1 = 1
global_variable_2 = 2
 
def update_variables():
    global global_variable_1
    global_variable_1 = 11
    global_variable_2 = 12 # will update just locally for this function
 
update_variables()
print(global_variable_1) # prints 11
print(global_variable_2) # prints 2

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。