根据 Go by Example 里的 Closures 实现,想用 Python 实现一下, 没有成功
Golang
package main
import "fmt"
func intSeq() func() int {
i := 0
return func() int {
i += 1
return i
}
}
func main() {
nextInt := intSeq()
fmt.Println(nextInt())
fmt.Println(nextInt())
fmt.Println(nextInt())
fmt.Println(nextInt())
// 一脸懵 为什么不重新初始化 intSeq(),值会一直添加???
newInts := intSeq()
fmt.Println(newInts())
}
输出
1
2
3
4
1
Python 2.7
# coding: utf-8
def intSeq():
def func():
i = 0
i += 1
return i
return func
if __name__ == "__main__":
nextInt = intSeq()
print nextInt()
print nextInt()
print nextInt()
print nextInt()
newInts = intSeq()
print nextInt()
输出结果:
1
1
1
1
1
话说 Python 中要怎么实现?