Discuss / Python / 打卡,作业

打卡,作业

Topic source

人玉匆花

#1 Created at ... [Delete] [Delete and Lock User]

1.利用闭包函数外函数中的变量

def createCounter():

    a = 0

    def counter():

        nonlocal a

        a = a+1

        return a

    return counter

2.利用生成器

def createCounter():

    def g():

        a = 1

        while True:

            yield a

            a = a+1

    t = g()

    # t =(a+1 for a in range(1000))

    def counter():

        return next(t)

    return counter

PS:1.最初的疑惑来自于变量的传递。2.考验了变量作用域和生成器的使用


  • 1

Reply