觉得有用的话,欢迎一起讨论相互学习~

【转】python中global的用法【转】python中global的用法【转】python中global的用法【转】python中global的用法
Python中定义函数时,若想在函数内部对函数外的变量进行操作,就需要在函数内部声明其为global。

例子1
x = 1

def func():
x = 2

func()
print(x)
输出:1
在func函数中并未在x前面加global,所以func函数无法将x赋为2,无法改变x的值

例子2
x = 1

def func():
global x
x = 2

func()
print(x)
输出:2
加了global,则可以在函数内部对函数外的对象进行操作了,也可以改变它的值了

例子3
global x
x = 1

def func():
x = 2

func()
print(x)
输出:1
global需要在函数内部声明,若在函数外声明,则函数依然无法操作


作者:xtingjie
来源:CSDN
原文:https://blog.csdn.net/xtingjie/article/details/71210182
版权声明:本文为博主原创文章,转载请附上博文链接!

相关文章:

  • 2022-12-23
  • 2021-08-05
  • 2021-07-23
  • 2022-12-23
  • 2021-09-16
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-12-29
  • 2021-11-29
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案