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
以上就是python变量声明为全局变量的两种方法,希望对大家有所帮助。更多Python学习指路:
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。
Copyright © 2019- yule263.com 版权所有 湘ICP备2023023988号-1
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务