首页 > 其他 > 详细

20201202-3 局部变量与全局变量作用域-1

时间:2020-12-02 19:55:50      阅读:24      评论:0      收藏:0      [点我收藏+]
技术分享图片
1-1
def test4(name,age=9999,*args,**kwargs):
    print(name)
    print(age)
    print(args)
    print(kwargs)
    logger("TEST4")

def logger(source):
    print("from %s" % source)

test4(itachi,age=21,sex=m,hobby=sweet_rice_ball)
--->
itachi
21
()
{sex: m, hobby: sweet_rice_ball}
from TEST4
运行结果没有问题
View Code
技术分享图片
1-2 局部变量
def change_name(name):
    print("before change",name)
    name = "Uchiha Itachi"
    print("after change",name)

name = itachi
change_name(name)
--->
before change itachi
after change Uchiha Itachi

# 局部变量,只在函数里生效;这个函数就是这个变量的作用域
View Code
技术分享图片
1-3
school = zxcv edu

def change_name(name):
    school = Mage Linux
    print(before change,name,school)
    name = Uchiha Itachi
    age = 23
    print(after change,name)

print(school)
name =itachi
change_name(name)
print(name)
--->
zxcv edu
before change itachi Mage Linux
after change Uchiha Itachi
itachi

# 全局变量,在函数中是改不了的,函数作用域只在小函数中生效
# 虽然叫同样的名字,但是没关系
# 函数中默认,局部变量无法修改全局变量
View Code
技术分享图片
1-4 如果想在局部变量中修改全局变量,应该怎么办? 声明 global
school = zxcv edu

def change_name(name):
    global school     # 在函数中修改全局变量
    school = Mage Linux
    print(before change,name,school)
    name = Uchiha Itachi
    age = 23
    print(after change,name)

name =itachi
change_name(name)
print(name)
print(school:,school)
--->
before change itachi Mage Linux
after change Uchiha Itachi
itachi
school: Mage Linux

# 这种情况是可以修改的
View Code

 

20201202-3 局部变量与全局变量作用域-1

原文:https://www.cnblogs.com/azxsdcv/p/14075058.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!