''''''
'''
global
Python中定义函数时,若想在函数内部对函数外的变量进行操作,就需要在函数内部声明其为global
只有声明为global,在函数内操作此变量才能影响此变量在函数外的值,否则,没有global就只是在函数内部使用这个变量的值,离开了函数,
这个变量还是原来的值,即函数内部对这个变量的操作没有影响其在函数外的值
'''
'''
#在funx函数中并未在x前面加global,所以funx函数无法将x赋为2,无法改变x的值
x = 1
def funx():
x=2
funx()
print(x)#1
'''
'''
#加了global,则可以在函数内部对函数外的对象进行操作了,也可以改变它的值了
x = 1
def funx():
global x
x+=1
funx()
print(x)#2
funx()
print(x)#3
funx()
print(x)#4
funx()
print(x)#5
funx()
print(x)#6
'''
'''
#global需要在函数内部声明,若在函数外声明,则函数依然无法操作x
global x
x = 1
def func():
x = 2
func()
print(x)#1
'''
'''
list = ['y']
def append():
list.append('x')
append()
print(list)#['y', 'x']
'''
python教程九(global方法)
最新推荐文章于 2024-09-14 08:25:16 发布