抽象
函数
- 判断某个对象是否可调用,可使用内置函数callable
>>> import math
>>> x = 1
>>> y = math.sqrt
>>> callable(x)
False
>>> callable(y)
True
- 斐波那契数组
def fibs(num): result = [0, 1] for i in range(num-2): result.append(result[-2] + result[-1]) return result
- 文档字符串
def square(x): 'Calculates the square of the number x.' return x * x>>> square.__doc__
'Calculates the square of the number x.'
-
所有的函数都返回值。如果你没有告诉它们该返回什么,将返回None
-
收集参数
def print_params(*params): print(params)
# 打印的是一个**元组**
>>> print_params('Testing')
('Testing',)
- 收集关键字参数
>>> def print_params_3(**params):
print(params)
# 打印的是一个**字典**
>>> print_params_3(x=1, y=2, z=3)
{'z': 3, 'x': 1, 'y': 2}
只有在定义函数(允许可变数量的参数)或调用函数时(拆分字典或序列)使用,星号才能发挥作用
作用域
- 为vars的内置函数,它返回这个不可见的字典
>>> x = 1
>>> scope = vars()
>>> scope['x']
1
>>> scope['x'] += 1
>>> x
2
- globals来访问全局变量, 返回一个包含全局变量的字典。(locals返回一个包含局部变量的字典。)
>>> def combine(parameter):
... print(parameter + globals()['parameter'])
...
>>> parameter = 'berry'
>>> combine('Shrub')
Shrubberry# 重新关联
>>> x = 1
>>> def change_global():
... global x
... x = x + 1
...
>>> change_global()
>>> x
2
递归
- 阶乘
- 1的阶乘为1。
- 对于大于1的数字n,其阶乘为n 1的阶乘再乘以n。
def factorial(n): if n == 1: return 1 else: return n * factorial(n - 1)
- 幂
- 对于任何数字x,power(x, 0)都为1。
- n>0时,power(x, n)为power(x, n-1)与x的乘积。
def power(x, n): if n == 0: return 1 else: return x * power(x, n - 1)
- 二分查找
- 如果上限和下限相同,就说明它们都指向数字所在的位置,因此将这个数字返回。
- 否则,找出区间的中间位置(上限和下限的平均值),再确定数字在左半部分还是右半部
分。然后在继续在数字所在的那部分中查找。
def search(sequence, number, lower=0, upper=None): if lower == upper: assert number == sequence[upper] return upper else: middle = (lower + upper) // 2 if number > sequence[middle]: return search(sequence, number, middle + 1, upper) else: return search(sequence, number, lower, middle)
小结
抽象:抽象是隐藏不必要细节的艺术。通过定义处理细节的函数,可让程序更抽象。
函数定义:函数是使用def语句定义的。函数由语句块组成,它们从外部接受值(参数),
并可能返回一个或多个值(计算结果)。
参数:函数通过参数(调用函数时被设置的变量)接收所需的信息。在Python中,参数有
两类:位置参数和关键字参数。通过给参数指定默认值,可使其变成可选的。
作用域:变量存储在作用域(也叫命名空间)中。在Python中,作用域分两大类:全局作
用域和局部作用域。作用域可以嵌套。
递归:函数可调用自身,这称为递归。可使用递归完成的任何任务都可使用循环来完成,
但有时使用递归函数的可读性更高。
函数式编程:Python提供了一些函数式编程工具,其中包括lambda表达式以及函数map、
filter和reduce。