Discuss / Python / 把大佬的作业整理下

把大佬的作业整理下

Topic source

不知小岛

#1 Created at ... [Delete] [Delete and Lock User]
1、使用列表的最简单明了:

def createCounter():
    count = [0]
    def counter():
        count[0] = count[0]+1
        return count[0]
    return counter
2、使用生成器也不错:

def createCounter():
    g = (i for i in range(1,1000))#定义一个生成器g
    def counter():
        return next(g)
    return counter
3、用nonlocal知识,了解后也很方便(需要查nonlocal,LEGB调用原则):

def createCounter():
    n = 0
    def counter():
        nonlocal n
        n = n+1
        return n
    return counter

活力老汤

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

写的好!


  • 1

Reply