Python函数式编程
Python函数式编程

1. 函数式编程简介

函数式编程是一种编程范式,强调使用函数作为基本构建块。与命令式编程相比,它更关注于表达计算的逻辑而不是步骤。

2. 高阶函数

高阶函数是接受函数作为参数或返回函数的函数。

示例:

1def square(x):
2    return x * x
3
4def apply_function(func, value):
5    return func(value)
6
7result = apply_function(square, 5)  # 输出: 25

3. 匿名函数

匿名函数使用 lambda 表达式定义,无需命名。

示例:

1add = lambda x, y: x + y
2result = add(3, 5)  # 输出: 8

4. 不可变数据结构

不可变数据结构如元组,确保数据不被修改。

示例:

1coordinates = (10, 20)
2# coordinates[0] = 15  # 会报错,元组不可变

5. 闭包

闭包是一个函数,其内部引用了外部函数的变量。

示例:

1def outer_function(x):
2    def inner_function(y):
3        return x + y
4    return inner_function
5
6closure = outer_function(10)
7result = closure(5)  # 输出: 15

6. 装饰器

装饰器用于在不修改函数代码的情况下增强其功能。

示例:

 1def decorator(func):
 2    def wrapper():
 3        print("Something is happening before the function is called.")
 4        func()
 5        print("Something is happening after the function is called.")
 6    return wrapper
 7
 8@decorator
 9def say_hello():
10    print("Hello!")
11
12say_hello()

7. 函数组合

函数组合是将多个函数合并为一个函数的过程。

示例:

 1def add_one(x):
 2    return x + 1
 3
 4def multiply_by_two(x):
 5    return x * 2
 6
 7def combined_function(x):
 8    return multiply_by_two(add_one(x))
 9
10result = combined_function(3)  # 输出: 8

8. 柯里化

柯里化是将多个参数的函数转换为一系列只接受一个参数的函数。

示例:

1def curried_add(x):
2    def add_y(y):
3        return x + y
4    return add_y
5
6add_five = curried_add(5)
7result = add_five(10)  # 输出: 15

最后修改于 2024-10-12 16:09