# 详解Python中的普通函数和高阶函数

## 什么是函数

Python中的函数也是一样的。

```def f(x):
print("参数为：",x)
return x
```

## 函数的嵌套调用

```def z(x):
pass
def f(x):
print("参数为：",x)
return z(x)
```

### 高阶函数

```def f(z):
return z()
```

```#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/10/24 11:39 下午
# @Author : LeiXueWei
# @CSDN/Juejin/Wechat: 雷学委
# @XueWeiTag: CodingDemo
# @File : func_demo2.py
# @Project : hello
def f1(x):
return x
def f2(x, z=100):
return x + z / 10
def f3(x, z=100, *dynamic_args):
sum = 0
for arg in dynamic_args:
sum += arg
return x + z / 10 + sum / 10000.0
def dummy_sum(*args):
return 0
def f4(x, z=100, sum_func=dummy_sum):
return x + z / 10 + sum_func() / 10000.0
print(f1(100))
print(f2(100, z=50))
print(f3(100, 50, 4, 5, 6))
def sum_g(*dynamic_args):
def sum_func():
sum = 0
for arg in dynamic_args:
sum += arg
return sum
return sum_func
print(f4(100, 50, sum_g(4, 5, 6)))
```

f3 和f4 看起来结果一样。

f4弹性非常大，因为第三个参数为函数。

## 我们思考一下计算圆形和方形的面积

```#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/10/24 11:39 下午
# @Author : LeiXueWei
# @CSDN/Juejin/Wechat: 雷学委
# @XueWeiTag: CodingDemo
# @File : func_demo2.py
# @Project : hello
import math
def circle_area(r):
return math.pi * r * r
def rectangle_area(a, b):
return a * b
```

f ( r ) = π ∗ r 2

f ( a , b ) = a ∗ b

```#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/10/24 11:39 下午
# @Author : LeiXueWei
# @CSDN/Juejin/Wechat: 雷学委
# @XueWeiTag: CodingDemo
# @File : func_demo2.py
# @Project : hello
import math
def circle_area(r):
return math.pi * r * r
def rectangle_area(a, b):
return a * b
def area(x, linear, factor):
return x * linear(x, factor)
def relation(x, factor):
return x * factor
a = 10
b = 20
print("长方形面积：", rectangle_area(a, b))
print("圆形面积：", circle_area(a))
print("长方形面积：", area(a, relation, factor=b / a))
print("圆形面积：", area(a, relation, factor=math.pi))
```

```#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/10/24 11:39 下午
# @Author : LeiXueWei
# @CSDN/Juejin/Wechat: 雷学委
# @XueWeiTag: CodingDemo
# @File : func_demo2.py
# @Project : hello
import math
def circle_area(r):
return math.pi * r * r
def square_area(a):
return a * a
def rectangle_area(a, b):
return a * b
def area(x, linear, factor):
return x * linear(x, factor)
def relation(x, factor):
return x * factor
a = 10
b = 20
print("长方形面积：", rectangle_area(a, b))
print("正方形面积：", square_area(a))
print("圆形面积：", circle_area(a))
print("长方形面积：", area(a, relation, factor=b / a))
print("正方形面积：", area(a, relation, factor=1))
print("圆形面积：", area(a, relation, factor=math.pi))
```

## 总结

```lambda  参数1， 参数2，。。。，第n个参数 ： 计算表达式
```

```print("长方形面积：", area(a, lambda x, f: x * f, factor=b / a))
print("正方形面积：", area(a, lambda x, f: x * f, factor=1))
print("圆形面积：", area(a, lambda x, f: x * f, factor=math.pi))
```