一、匿名函数(map, filter)
lambda 参数: 返回值
lambda arg: "我是%s" % arg
x = map(lambda obj: True, [1, 2, 3])
print(list(x))
二、闭包(函数外调用函数里面的函数)
1.获取函数是使用函数名
2.调用函数是使用函数名()
1 #闭包 2 def main(): 3 print("外函数") 4 def nest(): 5 print("被嵌套函数") 6 return nest 7 # x = main() 8 # x() 9 main()()
三、函数作用域(全局和局部)
全局变量(global)
i = 123 def test(): global i#声明全局变量 i = 111 def nest(): global i i = 4 return nest test() print(i)
局部变量(nonlocal)
def glo(): test_non = 34 def test(): nonlocal test_non #声明局部变量 test_non += 1#声明后可直接修改局部变量
四、回调函数和递归
回调函数:
def mm(x): if x in "asdf": callback() else: print("不调用") def callback():#回调函数 print("调用") mm("1")
递归(自己调用自己)
def recur(n): if n == 1:#while, 必须要有一个终止条件 return 1 return recur(n - 1) + 1 recur(5) # 作用和循环差不多 #限制:1.次数有限制 # 2.占用内存 ,成几何倍增长