Discuss / Python / 作业

作业

Topic source

松霜杨雪

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

def createCounter(): fs = [0] def counter(): fs[0] = fs[0] + 1 return fs[0] return counter

测试:

counterA = createCounter() print(counterA(), counterA(), counterA(), counterA(), counterA()) # 1 2 3 4 5 counterB = createCounter() if [counterB(), counterB(), counterB(), counterB()] == [1, 2, 3, 4]: print('测试通过!') else: print('测试失败!')

安天牛

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

666,巧妙利用了[]作为参数的特性

如果将这里的列表改为数字,如下 def createCounter(): fs = 0 def counter(): fs = fs + 1 return fs return counter 就会报一个UnboundLocalError: local variable 'fs' referenced before assignment的错误。有大神可以解释一下为什么将列表换成普通数字就不行了,这里不是特别明白。

主要是因为fs在counter被修改,变成了局部变量,如果在更改前又进行了读取操作,则会抛出异常。详见这篇文章:http://blog.csdn.net/miniykyk/article/details/52383960

妙哉

阳光漫射

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

example:

a = [1, 2, 3] b = a a[1] = 3 b = [1, 3, 3]

Interesting "List"


  • 1

Reply