2020python exercise 12 — function objects and closure functions (1)

Time:2020-12-1

 @2020.3.20 

1. Code practice of multi branch if optimized by function object
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. Write the counter function, call one time, add one on the original basis
        reminder:
            1: Need to use knowledge: closure function + nonlocal
            2: The core functions are as follows:
                def counter():
                    x+=1
                    return x


        The end result is required to be similar
            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())

 

Recommended Today

Alink tips: how to read batch CSV data?

Alink is a machine learning algorithm platform based on Flink. Please visit alink’s GitHub for more information. This article mainly shares one of the use skills of alink, how to use batch CSV to read data. basic operation Let’s download a CSV file to use as the test data. Download the data file locally, and […]