Python全局变量global

来源:互联网 发布:arm linux gcc 4.8 编辑:程序博客网 时间:2024/05/21 19:01

一个普通的例子

def func(x):    print('this is x:', x)    x = 2    print('this is new x:', x)x = 50func(x)print('this is also x:', x)>>>this is x: 50>>>this is new x: 2>>>this is also x: 50

第二个例子

def func():
    global x 
    print('this is x:', x)
    x = 2
    print('this is new x:', x)
x = 50
func()
print('this is also x:' ,x)
>>>this is x: 50
>>>this is new x: 2
>>>this is also x: 2 



所以在前面定义好全局变量后,会一直反映在之后任意的地方



原创粉丝点击