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
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!
