2009年03月31日

:

:
  1. >   function newCounter ()
  2. >>     local i = 0
  3. >>     return function ()   -- anonymous function
  4. >>              i = i + 1
  5. >>              return i
  6. >>            end
  7. >>   end
  8. >  
  9. >   c1 = newCounter()
  10. > print(c1())
  11. 1
  12. > print(c1())
  13. 2

类似,也可以嵌套定义函数,不过嵌套函数可以访问上层闭包函数的局部变量,而在这个内嵌函数中这些变量不是全局变量,也不是局部变量,而是一种upvalue,与C语言中的static修饰的变量类似,所以在这里可以利用这个特性完成这个计数器。

:

:
  1. >>> def counter(last=[1]):
  2.   ...     next = last[0] + 1
  3.   ...     last[0] = next
  4.   ...     return next
  5.   ...
  6.  >>> counter()
  7.   2
  8.  >>> counter()
  9.   3

今天看的时候觉得也应该有比较简单的办法写个计数器,找到一篇文章介绍这个小技巧,其中有一句话:

However, if named parameters are given mutable default values, the parameters can act as persistent memories of previous invocations. Lists, specifically, are handy mutable objects that can conveniently even hold multiple values.

作为一个嵌入式(嵌入到其它语言中)的脚本语言,在很多地方与类似,这几天在看Programming in

标签 :

随机日志

3 楼了已经

  • 草儿写于09年03月31日

    靠,你的文章对我来说越来越深奥了,都快成天书了。

  • tocer写于09年11月04日

    用 itertools.count 算不算?

    from itertools import count

    counter = count(1)
    for i in range(10):
    print counter.next()

  • cocobear写于09年11月05日

    没用过这个库 不错

发表评论

在下面加入你的评论,或者 trackback 从你的博客站点。 订阅本文的评论。

:

:

:

«
»