函数的作用域与匿名函数

1.函数作用域:从内到外寻找


def test():
name = 'Mike'
def test1():
name = 'John'
def test2():
name = 'Jack'
print(name)
return test2
return test1
print(test()) #只是打印出test1的内存地址
a = test()
a() # = test()() 运行test1
b = a()
b() # = test()()()运行test2 打印出jack

2.匿名函数:表示方法:lambda  形参:返回值

如果没有定义变量接收匿名函数,则匿名函数不会被内存处理,无意义

匿名函数形式简单,能进行的操作比较局限,仅限于数字运算,字符串增减,布尔值的判断以及多个变量简单处理等等

匿名函数通常不单独使用,与其他内置函数一起使用

1 a = lambda x:x**2
2 a1 = a(28)
3 print(a1)
4 b = lambda x:x+'我爱你!'
5 b1 = b('中国')
6 print(b1)
7 c = lambda x,y,z:(x**2,y+z)
8 c1 = c(12,123,222)  #注意多个变量处理时返回值要用括号括起
9 print(c1)

 

posted @ 2018-12-20 21:42  机智的小哥哥  阅读(146)  评论(0)    收藏  举报