讯享网
【教程领取方式在文末!!】
讯享网def foo():
print(‘foo’)
bar = foo
bar()
#will print ‘foo’ to the console
讯享网class Greeter:
def init(self, greeting):
self.greeting = greeting
def call(self, name):
return self.greeting + ‘ ’ + name
morning = Greeter(‘good morning’) #creates the callable object
morning(‘john’) # calling the object
#prints ‘good morning john’ to the console
讯享网callable(morning) #true
callable(145) #false. int is not callable.
# store in dictionary
mapping = {
0 : foo,
1 : bar
}
x = input() #get integer value from user
mappingx #call the func returned by dictionary access
「高阶函数允许我们对动作执行抽象,而不只是抽象数值。」
讯享网def iterate(list_of_items):
for item in list_of_items:
print(item)
看起来很酷吧,但这只不过是一级抽象而已。如果我们想在对列表执行迭代时进行打印以外的其他操作要怎么做呢?
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.
嵌套函数

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)
将该计算从函数主体移到函数参数,这具备非常强大的力量。因为它减少了递归方法中可能出现的冗余计算。
讯享网mult = lambda x, y: x y
mult(1, 2) #returns 2
该 mult 函数的行为与使用传统 def 关键字定义函数的行为相同。
(lambda x, y: x y)(9, 10) #returns 90
讯享网import collections
pre_fill = collections.defaultdict(lambda: (0, 0))
#all dictionary keys and values are set to 0
def 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 函数返回的 map 对象可被类型转换为 list,以方便使用。现在,我们无需显式地定义 multiply_by_four 函数,而是定义 lambda 表达式:
讯享网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 = 32
- Best 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/

获取方式:
- 点赞+再看
- 公众号内回复:“python”
领取2024年最新Python零基础学习资料,后台回复:Python
如果这篇文章对你有所帮助,还请花费2秒的时间点个赞+在看+分享,让更多的人看到这篇文章,帮助他们走出误区。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/181313.html