欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

2020Python作业12——函数对象和闭包函数(一)

程序员文章站 2022-03-26 11:12:21
@2020.3.20 ......

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