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

669次阅读
没有评论

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

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
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2022-03-21发表,共计533字。
新手QQ群:570568346,欢迎进群讨论 Python51学习