Python学习笔记(十八)- 高级函数话题(Advanced Function Topics)

1. lambda 表达式和 def 语句是如何联系的?
答:lambda 和 def 都创建稍后要调用的函数对象。 但是,因为lambda是一个表达式,它返回一个函数对象而不是将其赋值给一个名称,它可以用于在一个 def 语法不起作用的地方嵌套一个函数定义。 但是,lambda只允许一个隐式返回值表达式; 因为它不支持一个语句块,所以它不适合大型函数。

 

2.使用lambda有什么意义?
答:lambdas 允许我们“内联(inline)”可执行代码的小单元,推迟它的执行,并为其提供以默认参数和封闭范围变量形式状的态。 lambda 的使用从来都不是必要的; 您总是可以编写 def 代码并按名称引用该函数。 但是,lambda 有时来的很及时,可以嵌入不太可能在程序中其他地方使用的小块推迟的代码。 它们通常出现在基于回调(callback-based)的程序(如 GUI 程序中)中,并且它们与期望某个处理函数的 map 和 filter 等函数工具具有天然的联系。

Ps.map 与 filter 要传入一个函数,这个时候 lambda 就很有用了,因为lambda是表达式,所以可以以参数的形式传入它们中,而且写在 map 或者 filte r直接能看到函数具体的行为,不用向前找一段 def 语句(特别是很多代码时)。

 

3.比较和对比 map,filter 和reduce。
答:这三个内置函数都将另一个函数应用于序列(或其他可迭代)对象中的项并收集结果。 map 将每个项传递给函数并收集所有结果,filter 收集函数返回True值的项,reduce 通过将函数应用于累加器和连续项来计算单个值。 与其他前两个不同,要在3.X中的 functools 模块中才可以使用reduce,而不是内置范围; reduce 是2.X内置的。

 

4.什么是函数注释(function annotations),它们是如何使用的?
答:函数注释(3.X(3.0及更高版本)中提供)是函数参数和结果的语法修饰,它们被收集到分配给函数 __annotations__ 属性的字典中。 Python 在这些注释(annotations)中没有任何语义含义,但只是将它们打包以供其他工具使用。

e.g.

>>>def func(a:'spam', b:(1,10), c:float) -> int:
        return a + b + c
>>>func(1, 2, 3)
6
>>>func.__annotations__
{'a': 'spam', 'b': (1, 10), 'c': <class 'float'>, 'return': <class 'int'>}

 

5.什么是递归函数,它们是如何使用的?
答:递归函数直接或间接调用它们以循环。 它们可以用于遍历任意形状的结构,但它们也可以用于一般的迭代(尽管后一个角色通常用循环语句进行更简单有效地编写)。 递归通常可以通过使用显式堆栈(explicit stacks)或队列(queues)来对遍历进行更多控制的代码进行模拟(simulated)或替换(replaced)。

 

6.编写函数时一般设计指南是什么?
答:函数通常应该很小并且尽可能自给自足,具有单一的统一目的,并通过输入参数和返回值与其他组件通信/交流。 如果预期会发生变化,他们也可以使用可变参数来传达结果,并且某些类型的程序意味着其他通信机制(communication mechanisms)。

 

7.说出函数可以将结果传达给调用者(caller)的三种或更多种方式。
答:函数可以通过 return 语句,通过更改传入的可变参数以及设置全局变量来发回结果。 Globals 通常不赞成(除了非常特殊的情况,比如多线程程序),因为它们会使代码更难以理解和使用。 return 语句通常是最好的,但是如果需要,改变可变对象是件好事(甚至是有用的)。 函数也可以与系统设备(如 files 和 sockets)进行通信,但这些超出了我们这本书的范围。

 

一些其它的什么东西:

cohesion - n.凝聚,内聚;(各部的)结合;[力]内聚力;[植]连着

coupling - n.联结;[电]耦合;[机]管箍;(火车的)车钩
                 v.连接(couple的现在分词)

编写函数的指南

1.耦合(coupling ):输入使用参数,输出返回参数

2.耦合(coupling ):只有当真正需要的时候,才使用全局变量

3.耦合(coupling ):除非调用者(caller)期望,否者不要使用可变参数

4.凝聚(cohesion ):每一个函数应有一个统一的目的

5.大小(size):每一个函数应当相对小 【Keep it simple, and keep it short.】

6.耦合(coupling ):避免直接更改另一个模块文件中的变量(尽可能使用访问器函数(accessor function),而不是直接赋值语句)

递归(recursion):允许程序遍历具有任意和不可预测的形状和深度的结构

直接递归:

def mysum(L):
    if not L:
        reuturn 0
    else:
        return L[0] + mysum(L[1:])

间接递归:
 

def mysum(L):
    if not L:
        return 0
    return nonempty(L)

def nonempty(L):
    return L[0] + mysum(L[1:])

递归可以处理随意的架构

L = [1, [2, [3, 4], 5], 6, [7, 8]] #嵌套随意深度和形状
def sumtree(L):
    tot = 0
    for x in L:
        if not isinstance(x, list):
           tot += x
        else: 
            tot += sumtree(x)  #对子列表递归
    return tot

递归限制:

>>>sys.getrecursionlimit()
1000
>>>sys.getrecursionlimit(10000)
>>>help(sys.getrecursionlimit)

函数注释(function annotations):

>>>def func(a:'spam'=4, b:(1, 10)=5, c:float=6) -> int: #默认值仍能使用,吐槽:好奇怪+好神奇
        return a + b + c
>>>func(1, 2, 3)
6
>>>func()
15

 

标注:转载《Learning Python 5th Edition》[奥莱理]
1. How are lambda expressions and def statements related?
2. What’s the point of using lambda?
3. Compare and contrast map, filter, and reduce.
4. What are function annotations, and how are they used?
5. What are recursive functions, and how are they used?
6. What are some general design guidelines for coding functions?
7. Name three or more ways that functions can communicate results to a caller.

1. Both lambda and def create function objects to be called later. Because lambda is an expression, though, it returns a function object instead of assigning it to a name, and it can be used to nest a function definition in places where a def will not work syntactically. A lambda allows for only a single implicit return value expression, though; because it does not support a block of statements, it is not ideal for larger functions.
2. lambdas allow us to “inline” small units of executable code, defer its execution, and provide it with state in the form of default arguments and enclosing scope variables. Using a lambda is never required; you can always code a def instead and reference the function by name. lambdas come in handy, though, to embed small pieces of deferred code that are unlikely to be used elsewhere in a program. They commonly appear in callback-based programs such as GUIs, and they have a natural affinity with functional tools like map and filter that expect a processing function.
3. These three built-in functions all apply another function to items in a sequence (or other iterable) object and collect results. map passes each item to the function and collects all results, filter collects items for which the function returns a True value, and reduce computes a single value by applying the function to an accumulator and successive items. Unlike the other two, reduce is available in the functools module in 3.X, not the built-in scope; reduce is a built-in in 2.X.
4. Function annotations, available in 3.X (3.0 and later), are syntactic embellishments of a function’s arguments and result, which are collected into a dictionary assigned to the function’s __annotations__ attribute. Python places no semantic meaning on these annotations, but simply packages them for potential use by other tools.
5. Recursive functions call themselves either directly or indirectly in order to loop. They may be used to traverse arbitrarily shaped structures, but they can also be used for iteration in general (though the latter role is often more simply and efficiently coded with looping statements). Recursion can often be simulated or replaced by code that uses explicit stacks or queues to have more control over traversals.
6. Functions should generally be small and as self-contained as possible, have a single unified purpose, and communicate with other components through input arguments and return values. They may use mutable arguments to communicate results too if changes are expected, and some types of programs imply other communication mechanisms.
7. Functions can send back results with return statements, by changing passed-in mutable arguments, and by setting global variables. Globals are generally frowned upon (except for very special cases, like multithreaded programs) because they can make code more difficult to understand and use. return statements are usually best, but changing mutables is fine (and even useful), if expected. Functions may also communicate results with system devices such as files and sockets, but these are beyond our scope here.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值