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

发布时间:2023-01-06 09:33:04 人气:88 作者:多测师

  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()

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

  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学习指路:请关注多测师。https://www.e70w.com/xwzx/




返回列表
在线客服
联系方式

热线电话

17727591462

上班时间

周一到周五

二维码
线