在Python中,装饰器(Decorator)和lambda函数(Lambda)是两种强大的工具,经常被用来提高代码的模块性、可读性和复用性。
装饰器
装饰器本质上是一个函数,它接受一个函数作为参数,并返回一个新的函数。这个新函数通常会“包装”或“增强”原始函数的功能。装饰器通常用来添加额外的功能,如日志记录、性能测试、事务处理、缓存等。
示例:使用装饰器
def my_decorator(func):
def wrapper():
print(“Something is happening before the function is called.”)
func()
print(“Something is happening after the function is called.”)
return wrapper
@my_decorator
def say_hello():
print(“Hello!”)
say_hello()
Lambda函数
Lambda函数是Python中一种匿名函数,它只能有一个表达式,表达式的计算结果就是函数的返回值。Lambda函数通常用于定义简短的、不需要复杂逻辑的函数。
示例:使用Lambda函数