函数的小高级
1.1函数名作为变量名使用
1 def func(): 2 print(123) 3 ret = func 4 ret() 5 6 7 def func(): 8 print(123) 9 func_list = [func,func,func] 10 for item in func_list: 11 v = item() 12 print(v) 13 14 15 def func(): 16 print(123) 17 def bar(): 18 print(666) 19 info = {'k1':func,'k2':bar} 20 info['k1']() 21 info['k2']() 22 23 24 def func(): 25 return 123 26 func_list1 = [func,func,func] 27 func_list2 = [func(),func(),func()] 28 print(func_list1) 29 print(func_list2) 30 31 info = { 32 'k1':func, 33 'k2':func() 34 } 35 print(info) #打印返回值
1.2 函数作为参数进行传递
1 def func(args): 2 print(args) #打印函数的地址 3 def show(): 4 return 999 5 func(show) 6 7 8 def func(args): 9 v1 = args() 10 print(v1) 11 def show(): 12 print(66) 13 func(show) 14
1.3 函数名+()无论在哪都是调用函数
2.内置函数
lambda函数
1 def func(a1,a2): 2 return a1 + 100 3 print(func(1)) 4 5 通过lambda表达式简化: 6 func = lambda a1,a2 :a1+100 #a1和a2相当于形参;a1+100相当于return返回值 7 print(func(1)) 8 9 func1 = lambda : 100 #相当于没有参数,直接返回100 10 11 func2 = lambda x1: x1 * 10 12 13 func3 = lambda *args,**kwargs: len(args) + len(kwargs) 14 DATA = 100 15 func4 = lambda a1: a1 + DATA 16 17 v = func4(1) 18 print(v) 19 DATA = 100 20 def func(): 21 DATA = 1000 22 func4 = lambda a1: a1 + DATA 23 v = func4(1) 24 print(v) 25 func() 26 27 func5 = lambda n1,n2: n1 if n1 > n2 else n2 28 v = func5(1111,2) 29 print(v)
1 User_list = [] 2 def func0(x): 3 v = User_list.append(x) 4 return v #没有返回值 5 result = func0('tom') 6 print(result)