1、在函数内部分配变量并使用global line。
defdeclare_a_global_variable(): globalglobal_variable_1 global_variable_1=1 #Notetousethefunctiontoglobalvariables declare_a_global_variable()
2、在函数外赋值。如果想在另一个函数中更改global line,update_variables()应该在分配变量之前使用global。
global_variable_1=1 global_variable_2=2 defupdate_variables(): globalglobal_variable_1 global_variable_1=11 global_variable_2=12#willupdatejustlocallyforthisfunction update_variables() print(global_variable_1)#prints11 print(global_variable_2)#prints2
以上就是python变量声明为全局变量的两种方法,希望对大家有所帮助。更多Python学习指路:Python基础教程
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
评论(0)