## 1. 高阶函数

• 被赋值给变量；
• 作为参数传递给函数；
• 作为返回值。

• 被赋值给变量；
• 作为参数传递给函数；
• 作为返回值。

### 1.2 把函数作为输入参数

``````def double(item):
return item + item

def triple(item):
return item + item + item
``````

``````def map(func, input):
output = []
for item in input:
new_item = func(item)
output.append(new_item)
return output
``````

``````print(map(double, [1, 2, 3]))
print(map(triple, [1, 2, 3]))
``````

``````[2, 4, 6]
[3, 6, 9]
``````

### 1.3 把函数作为返回值

``````def func():
print('Inside func')

def return_func():
print('Inside return_func')
return func
``````

``````var = return_func()
var()
``````

``````Inside return_func
Inside func
``````

• 输入参数是函数；
• 输出返回值是函数。

## 3. 装饰器的用途

### 3.1 需求

• quick_sort，快速排序；
• bubble_sort，冒泡排序；
• select_sort，选择排序。

``````import time

def quick_sort():
time.sleep(1)

def bubble_sort():
time.sleep(2)

def select_sort():
time.sleep(3)
``````

### 3.2 不使用装饰器

``````import time

def quick_sort():
start_time = time.time()
time.sleep(1)
end_time = time.time()
print('%.2f seconds' % (end_time - start_time))
``````

``````def bubble_sort():
start_time = time.time()
time.sleep(2)
end_time = time.time()
print('%.2f seconds' % (end_time - start_time))

def select_sort():
start_time = time.time()
time.sleep(3)
end_time = time.time()
print('%.2f seconds' % (end_time - start_time))
``````

``````quick_sort()
bubble_sort()
select_sort()
``````

``````1.00 seconds
2.00 seconds
3.00 seconds
``````

### 3.3 使用装饰器

• quick_sort、bubble_sort、select_sort 存在代码重复；
• 在函数头部记录开始时间、在函数尾部记录结束时间，逻辑是完全相同的。

``````import time

def quick_sort():
time.sleep(1)

def bubble_sort():
time.sleep(2)

def select_sort():
time.sleep(3)
``````

``````def decorate(input_sort):
def output_sort():
start_time = time.time()
input_sort()
end_time = time.time()
print('%.2f seconds' % (end_time - start_time))

return output_sort
``````

``````quick_sort = decorate(quick_sort)
bubble_sort = decorate(bubble_sort)
select_sort = decorate(select_sort)
``````

``````quick_sort()
bubble_sort()
select_sort()
``````

``````1.00 seconds
2.00 seconds
3.00 seconds
``````

## 4. Python 的装饰器语法

### 4.1 装饰器语法

``````def decorate(input_function):
def output_function():
pass
return output_function

@decorate
def input_function():
pass
``````

``````def decorate(input_function):
def output_function():
pass
return output_function

def input_function():
pass

input_function = decorate(input_function)
``````

decorate 函数接受输入参数 input_function，返回一个功能增强的函数 output_function。 用功能增强的新函数 output_function 替换原有的旧函数 input_function。

### 4.2 使用装饰器语法

``````import time

def decorate(input_sort):
def output_sort():
start_time = time.time()
input_sort()
end_time = time.time()
print('%.2f seconds' % (end_time - start_time))

return output_sort
``````

``````@decorate
def quick_sort():
time.sleep(1)

@decorate
def bubble_sort():
time.sleep(2)

@decorate
def select_sort():
time.sleep(3)
``````

``````quick_sort()
bubble_sort()
select_sort()
``````

``````1.00 seconds
2.00 seconds
3.00 seconds
``````