闭包
def outer(logo):
def inner(msg):
print(f"<{logo}>{msg}<{logo}>")
return inner
func_1 = outer("####")
print(type(func_1))
func_1("jsy")
func_2 = outer("$$$$$")
func_2('hello')
nonlocal关键字,在闭包中修改外部函数变量
def outer(num1):
def inner(num2):
nonlocal num1
num1 += num2
print(num1)
return inner
func_3 = outer(1)
func_3(2)
func_3(2)
闭包实现ATM案例
def account_create(init_money):
def atm(num, deposit=True):
nonlocal init_money
if deposit:
init_money += num
print(f"存钱:+{num},余额:{init_money}")
else:
init_money -= num
print(f"取钱:-{num},余额:{init_money}")
return atm
atm = account_create(0)
atm(100)
atm(100)
atm(200, False)