python 内函数 闭包 装饰器
内函数(Nested Functions)
内函数是定义在另一个函数内部的函数。内函数可以访问创建它的外部函数的变量。这使得内函数非常适合用于封装只在一个特定上下文中有用的功能。
def outer_function(x):
def inner_function(y):
return x + y
return inner_function
# 使用内函数
add_five = outer_function(5)
print(add_five(3)) # 输出 8
闭包(Closures)
闭包是由函数和与其相关的引用环境组合而成的实体。在Python中,闭包通常由内函数创建,并且即使创建它的外部函数已经执行完毕,闭包仍然可以访问外部函数的局部变量。
def make_adder(x):
def adder(y):
return x + y
return adder
# 创建闭包
add_five = make_adder(5)
add_three = make_adder(3)
print(add_five(2)) # 输出 7
print(add_three(5)) # 输出 8
装饰器(Decorators)
装饰器是一种设计模式,用于修改或增强函数、方法或类的行为,而不需要改变其本身的代码。装饰器本质上是一个接受函数作为参数并返回一个函数的函数。
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()
my_decorator 是一个装饰器,它增强了 say_hello 函数的行为,在函数调用前后分别打印了一些文本