Python函数的变量域

变量作用域
Python作用域一共分为四种,分别是:
L 局部作用域
E 闭包函数外的函数中
G 全局作用域
B 内建作用域

变量的查找是以 L E G B的规则顺序查找的。 现在局部中招,找不到变会去局部外的局部找(例如闭包)
Python中只有模块,累,以及函数def,lambda,才会引入新的工作域

实例:
total = 0
n2 = 10
def sum(m,p):
    print(n2)
    total = m + p
    print("函数是局部变量total:" ,total)
    return total
sum(10,20)
print("函数外是全局变量total",total)

打印结果

10
函数是局部变量total: 30
函数外是全局变量total 0

匿名函数

语法: lambda[参数1[参数2,参数3,..参数n] : 表达式

实例:

g = lambda x:x*x+1
print(g(1))
print(g(2))

输出结果:

D:\python_install\py3.5\python.exe 
2
5

Process finished with exit code 0

猜你喜欢

转载自blog.csdn.net/xinshuzhan/article/details/80216879
今日推荐