闭包
# 闭包
def outer(logo):def inner(msg):print(f"<{logo}>{msg}<{logo}>")return inner
fn1 = outer("Hello") # 类型是函数 注意这里传入的参数对于内部函数来说是持续存在的
fn1("world")
# 修改外部函数的值
def out(num1):def In(num2):nonlocal num1num1 += num2print(num1)return In
fn = out(10)
fn(10)
fn(10)
# 案例
def account_create(init_account=0):def atm(num, deposit=True):nonlocal init_accountif deposit == True:init_account += numprint(init_account)else:init_account -= numprint(init_account)return atm
atm = account_create()
atm(100)
atm(50, False)
# 总结:闭包优点是无需定义全局变量即可实现通过函数持续访问、修改某个值,闭包使用的变量难以被错误的调用修改
装饰器
# 装饰器
def sleep():import randomimport timeprint("睡眠中...")time.sleep(random.randint(1, 5))
def outer(func):def inner():print("我睡觉了")func()print("我起床了")return inner
fn = outer(sleep)
fn()
# 装饰器快速写法
@outer
def sleep2():import randomimport timeprint("睡眠中...")time.sleep(random.randint(1, 5))
sleep2()