@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]()

 

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
 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())

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄