1. 匿名函数:lambda 的使用及特性
1.1 lambda 函数的基本用法
lambda
是 Python 中用于创建匿名函数的关键字。与普通函数使用 def
定义不同,lambda
函数通常用于定义一些简单、临时的函数。其语法格式如下:
lambda 参数1,参数2,参数3....: 表达式
例如,我们可以使用 lambda
来创建一个简单的加法函数:
#lambda 函数接收两个参数 x 和 y,并返回它们的和。
add = lambda x, y: x + y
print(add(3, 5)) # 输出 8
1.2 lambda 函数的特性
- 匿名性:它是没有名字的函数,并且自带return,可以直接在表达式中使用。
- 返回值:lambda函数返回一个值,这个值就是表达式的结果。
- 只能包含一个表达式:可以使用任意数量的参数,但只能包含一个表达式。
-
生命周期很短:生命周期很短,调用后立即被回收。
2. 高阶函数
在 Python 中,函数可以作为参数传递给其他函数,也可以作为返回值返回,这些函数被称为高阶函数。常见的高阶函数包括 map()
、reduce()
、filter()
和 sorted()
等。
2.1 map 函数
map()
函数接受一个函数和一个可迭代对象(如列表、元组等),并将该函数应用到可迭代对象中的每个元素上,返回一个新的迭代器。
格式:
map(函数,可迭代对象)
其基本用法如下:
# 例:将列表中的每个数字乘以 2
numbers = [1, 2, 3, 4]
result = map(lambda x: x * 2, numbers)
print(list(result)) # 输出 [2, 4, 6, 8]
2.2 reduce 函数
reduce()
是 functools
模块中的一个函数,它接受一个二元操作函数和一个可迭代对象,并通过累积的方式将该操作应用到可迭代对象的每个元素上,最终返回一个值。
格式:
from functools import reduce
reduce(函数,可迭代对象)
其基本用法如下:
from functools import reduce
# 例:求列表所有数字的积
numbers = [1, 2, 3, 4]
result = reduce(lambda x, y: x * y, numbers)
print(result) # 输出 24
2.3 filter 函数
filter()
函数接受一个函数和一个可迭代对象,返回一个新的可迭代对象,包含所有使得函数返回 True
的元素。
格式:
filter(函数, 可迭代对象)
其基本用法如下:
# 例:筛选出列表中的偶数
numbers = [1, 2, 3, 4, 5, 6]
result = filter(lambda x: x % 2 == 0, numbers)
print(list(result)) # 输出 [2, 4, 6]
2.4 排序函数:sorted
sorted()
函数用于对可迭代对象进行排序,并返回一个新的列表。其基本用法如下:
# 例:按字母顺序排序
words = ['banana', 'apple', 'cherry']
result = sorted(words)
print(result) # 输出 ['apple', 'banana', 'cherry']
sort:
sort()
方法与 sorted()
类似,但它是列表对象的方法,会直接修改原列表而不是返回一个新的列表。
# 例:对列表进行排序
numbers = [4, 2, 3, 1]
numbers.sort()
print(numbers) # 输出 [1, 2, 3, 4]
3. 装饰器
3.1 装饰器的概念
在python中,装饰器本质是一个特殊的嵌套函数,它接收一个函数【被装饰的函数】做参数,并返回一个新的函数【装饰后的函数】
装饰器的最大作用:在不改变原有函数【被装饰的函数】的基础上给它添加新的功能。
3.2 装饰器的基本用法
最简单的装饰器是一个接受函数作为参数,并返回一个修改后的函数。以下是一个基础的装饰器例子:
def decorator(func):
def wrapper():
print("Before the function call.")
func()
print("After the function call.")
return wrapper
@decorator
def say_hello():
print("Hello!")
say_hello()
输出:
Before the function call.
Hello!
After the function call.
在这个例子中,@decorator
是装饰器的语法糖,相当于 say_hello = decorator(say_hello)
。
3.3 装饰器语法糖
格式:
@装饰器函数名
def 被装饰函数名:
代码块
其实就是在被装饰函数的上面加一句话——@装饰器
例如:
# 装饰器
def out_fun(function):
def in_fun():
print("挂上一颗星星")
function()
print("挂上一个礼物盒")
return in_fun
# 被装饰函数
@out_fun
def my_tree():
print("简简单单一棵树")
my_tree()
输出:
挂上一颗星星
简简单单一棵树
挂上一个礼物盒
3.4 被装饰函数有参数
若被装饰函数有参数,那么装饰器的内部函数也需要有参数,保证在内部调用被装饰函数的时候能正确传参。
3.4.1 被装饰函数有一个参数
如果被装饰的函数带有参数,我们可以在装饰器中修改 wrapper
函数,传递这些参数:
def decorator(func):
def wrapper(name):
print("Before the function call.")
func(name)
print("After the function call.")
return wrapper
@decorator
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
输出:
Before the function call.
Hello, Alice!
After the function call.
3.4.2 被装饰函数有未知个参数
如果被装饰的函数有多个参数,可以使用 *args
和 **kwargs
来接收任意数量的位置参数和关键字参数:
def decorator(func):
def wrapper(*args, **kwargs):
print("Before the function call.")
func(*args, **kwargs)
print("After the function call.")
return wrapper
@decorator
def greet(name, age):
print(f"Hello, {name}. You are {age} years old.")
greet("Bob", 25)
输出:
Before the function call.
Hello, Bob. You are 25 years old.
After the function call.
3.5 装饰器带参数
有时我们希望装饰器能接受参数,这就需要在装饰器函数外再嵌套一层函数:
def repeat_decorator(times):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(times):
func(*args, **kwargs)
return wrapper
return decorator
@repeat_decorator(3)
def greet(name):
print(f"Hello, {name}!")
greet("Charlie")
输出:
Hello, Charlie!
Hello, Charlie!
Hello, Charlie!
3.6 装饰器嵌套
装饰器可以嵌套使用,也就是说,多个装饰器可以作用于同一个函数。装饰器会按照从下到上的顺序应用:
def decorator_one(func):
def wrapper():
print("Decorator One")
func()
return wrapper
def decorator_two(func):
def wrapper():
print("Decorator Two")
func()
return wrapper
@decorator_one
@decorator_two
def greet():
print("Hello!")
greet()
输出:
Decorator One
Decorator Two
Hello!
3.7 类装饰器
除了可以自定义一个新的函数用作装饰器之外,也可以将一个类作为装饰器,为被装饰的函数添加新的功能。类装饰器通过实现类的__call__方法,使得类的实例可以被当作函数来调用,丛而实现对其他函数的装饰。