feat: python
This commit is contained in:
@@ -0,0 +1,90 @@
|
||||
# 详细说明闭包的概念、工作原理、使用场景、优势以及在实际开发中的应用价值
|
||||
|
||||
# 1. 闭包概述
|
||||
# 闭包(Closure)是Python中的一种独特的函数机制。简而言之,闭包是指在一个内部函数中,引用了外部函数的变量,而这个外部函数已经执行完毕并返回了内部函数,然而内部函数仍然可以访问这些外部函数中的变量。
|
||||
|
||||
# 核心特点
|
||||
|
||||
# 内部函数:闭包涉及内部函数和外部函数
|
||||
# 变量引用:内部函数引用外部函数的变量
|
||||
# 状态保持:外部函数执行完毕后,内部函数仍能访问外部变量
|
||||
# 数据封装:通过闭包可以实现数据的封装和隐藏
|
||||
|
||||
|
||||
def out_function(x):
|
||||
def inner_function(y):
|
||||
return x + y
|
||||
|
||||
return inner_function
|
||||
|
||||
|
||||
func = out_function(1)
|
||||
result = func(4)
|
||||
print(result)
|
||||
|
||||
# 闭包和作用域链
|
||||
# 闭包依赖于 Python 的词法作用域规则:内部函数会自动捕获其外部作用域内用到的变量,这些变量在外部函数生命周期结束后也不会被销毁。
|
||||
|
||||
# 2.2.3 使用 nonlocal 修改闭包变量
|
||||
# 通常,闭包内部只能“读取”外部变量。如果想在内部函数中“修改”外部函数的变量,需要使用 nonlocal 关键字。例如:
|
||||
|
||||
|
||||
def make_accumulator(base=0):
|
||||
total = base
|
||||
|
||||
def add(num):
|
||||
nonlocal total
|
||||
total += num
|
||||
return total
|
||||
|
||||
return add
|
||||
|
||||
|
||||
acc = make_accumulator(10)
|
||||
print(acc(20))
|
||||
print(acc(-1))
|
||||
|
||||
|
||||
# 简单的装饰器
|
||||
def my_decorator(func):
|
||||
def wrapper(*args, **kwargs):
|
||||
print(f"调用函数:{func.__name__}")
|
||||
result = func(*args, **kwargs)
|
||||
print(f"函数 {func.__name__} 执行完成")
|
||||
return result
|
||||
|
||||
return wrapper
|
||||
|
||||
|
||||
@my_decorator
|
||||
def greet(name):
|
||||
return f"Hello,{name}"
|
||||
|
||||
|
||||
result = greet("小明")
|
||||
print(result)
|
||||
|
||||
# 带参数的装饰器
|
||||
|
||||
|
||||
def repeat(num):
|
||||
def decorator(func):
|
||||
def warpper(*args, **kwargs):
|
||||
results = []
|
||||
for i in range(num):
|
||||
result = func(*args, **kwargs)
|
||||
results.append(result)
|
||||
return results
|
||||
|
||||
return warpper
|
||||
|
||||
return decorator
|
||||
|
||||
|
||||
@repeat(3)
|
||||
def say_hello(name):
|
||||
return f"Hello {name}"
|
||||
|
||||
|
||||
results = say_hello("小明")
|
||||
print(results)
|
||||
Reference in New Issue
Block a user