@2020.3.20
1、函数对象优化多分支if的代码练熟
def foo(): print('foo') def bar(): print('bar') dic={ 'foo':foo, 'bar':bar, } while True: choice=input('>>: ').strip() if choice in dic: dic[choice]()
2、编写计数器功能,要求调用一次在原有的基础上加一 温馨提示: I:需要用到的知识点:闭包函数+nonlocal II:核心功能如下: def counter(): x+=1 return x 要求最终效果类似 print(couter()) # 1 print(couter()) # 2 print(couter()) # 3 print(couter()) # 4 print(couter()) # 5
def f1(): x=0 def counter(): nonlocal x x+=1 return x return counter counter=f1() print(counter()) print(counter()) print(counter()) print(counter()) print(counter())
来源:https://www.cnblogs.com/bigorangecc/p/12534864.html