Python 函數(shù)式編程,看這一篇就夠了!



def foo():
print("foo")bar = foo
bar()
#will print "foo" to the consoleclass Greeter:
def __init__(self, greeting):
self.greeting = greeting
def __call__(self, name):
return self.greeting + " " + namemorning = Greeter("good morning") #creates the callable object
morning("john") # calling the object
#prints "good morning john" to the consolecallable(morning) #true
callable(145) #false. int is not callable. # store in dictionary
mapping = {
0 : foo,
1 : bar
}
x = input() #get integer value from user
mapping[x]() #call the func returned by dictionary access「高階函數(shù)允許我們對動(dòng)作執(zhí)行抽象,而不只是抽象數(shù)值?!?/span>
def iterate(list_of_items):
for item in list_of_items:
print(item)
看起來很酷吧,但這只不過是一級抽象而已。如果我們想在對列表執(zhí)行迭代時(shí)進(jìn)行打印以外的其他操作要怎么做呢?
def iterate_custom(list_of_items, custom_func):
for item in list_of_items:
custom_func(item)def add(x, y):
return x + y
def sub(x, y):
return x - y
def mult(x, y):
return x * y
def calculator(opcode):
if opcode == 1:
return add
elif opcode == 2:
return sub
else:
return mult
my_calc = calculator(2) #my calc is a subtractor
my_calc(5, 4) #returns 5 - 4 = 1
my_calc = calculator(9) #my calc is now a multiplier
my_calc(5, 4) #returns 5 x 4 = 20.
嵌套函數(shù)
def fib(n):
def fib_helper(fk1, fk, k):
if n == k:
return fk
else:
return fib_helper(fk, fk1+fk, k+1)
if n <= 1:
return n
else:
return fib_helper(0, 1, 1)
將該計(jì)算從函數(shù)主體移到函數(shù)參數(shù),這具備非常強(qiáng)大的力量。因?yàn)樗鼫p少了遞歸方法中可能出現(xiàn)的冗余計(jì)算。
mult = lambda x, y: x * y
mult(1, 2) #returns 2
該 mult 函數(shù)的行為與使用傳統(tǒng) def 關(guān)鍵字定義函數(shù)的行為相同。
(lambda x, y: x * y)(9, 10) #returns 90import collections
pre_fill = collections.defaultdict(lambda: (0, 0))
#all dictionary keys and values are set to 0def multiply_by_four(x):
return x * 4
scores = [3, 6, 8, 3, 5, 7]
modified_scores = list(map(multiply_by_four, scores))
#modified scores is now [12, 24, 32, 12, 20, 28]
在 Python 3 中,map 函數(shù)返回的 map 對象可被類型轉(zhuǎn)換為 list,以方便使用?,F(xiàn)在,我們無需顯式地定義 multiply_by_four 函數(shù),而是定義 lambda 表達(dá)式:
modified_scores = list(map(lambda x: 4 * x, scores))even_scores = list(filter(lambda x: True if (x % 2 == 0) else False, scores))
#even_scores = [6, 8]sum_scores = reduce((lambda x, y: x + y), scores)
#sum_scores = 32Best Practices for Using Functional Programming in Python:https://kite.com/blog/python/functional-programming/
Functional Programming Tutorials and Notes:https://www.hackerearth.com/zh/practice/python/functional-programming/functional-programming-1/tutorial/
原文鏈接:https://medium.com/better-programming/introduction-to-functional-programming-in-python-3d26cd9cbfd7
END
推薦閱讀
牛逼!Python常用數(shù)據(jù)類型的基本操作(長文系列第①篇)
牛逼!Python的判斷、循環(huán)和各種表達(dá)式(長文系列第②篇)
吳恩達(dá)deeplearining.ai的經(jīng)典總結(jié)資料
Ps:從小程序直接獲取下載
