天天看點

Python-3 匿名函數

#1、匿名函數計算a+b的值

func = lambda a,b:a+b

result = func(2,3) #傳入實參2和3,計算a+b,自動傳回a+b的值。與def 函數相比,不需要return。

print("result=%d"%result)

實際輸出:
>>result=5           

複制

#2、輸入一個匿名函數,傳入匿名函數參數,在def函數中調用此匿名函數。

def test(a,b,func):

result = func(a,b)
            print("result=%d"%result)           

複制

func = input("請輸入一個匿名函數:")

func = eval(func) #字元串不能被調用,使用eval函數 轉成可被調用的函數。

test(11,22,func)

實際輸出:

請輸入一個匿名函數:lambda x,y:x+y-3

30