根据 Go by Example 里的 Closures 实现,想用 Python 实现一下, 没有成功
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
# 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 中要怎么实现?
1
Arnie97 Dec 22, 2017 via Android def seq():
....i = 0 ....def func(): ........i += 1 ........return i ....return func |
2
rabbbit Dec 22, 2017 def intSeq():
i = [0] def func(): i[0] += 1 return i[0] return func if __name__ == "__main__": nextInt = intSeq() print nextInt() print nextInt() print nextInt() print nextInt() newInts = intSeq() print nextInt() |
3
awker OP |
4
Arnie97 Dec 22, 2017 via Android 一楼笔误,少贴了一行 nonlocal。
def seq(): ....i = 0 ....def func(): ........nonlocal i ........i += 1 ........return i ....return func |
6
rabbbit Dec 22, 2017 newInts = intSeq()
print nextInt() to nextInt = intSeq() print nextInt() |
8
awker OP |
9
xpresslink Dec 22, 2017 因为 Python 不需这么玩唉
Python 的哲学是不要自己造轮子。 >>> def g_factory(): i = 1 while True: yield i i += 1 >>> g = g_factory() >>> next(g) 1 >>> next(g) 2 >>> >>> from itertools import count >>> c = count(1) >>> next(c) 1 >>> next(c) 2 >>> >>> from itertools import cycle >>> c = cycle([1,2,3]) >>> next(c) 1 >>> next(c) 2 >>> next(c) 3 >>> next(c) 1 >>> |
10
julyclyde Dec 22, 2017 为什么大家这么爱好实现一个有状态的函数?
这需求不是应该用对象吗? |
11
araraloren Dec 22, 2017 @xpresslink The key point is not `how to implement a generator`.
|
12
araraloren Dec 22, 2017 |
13
xpresslink Dec 22, 2017 @araraloren To implement a generator is must-know trick for pythoneer, the key point is 'how to solve the problem or fulfill the requirement. you are using Python, you should obey its philosophy. generator is better solution, if you just want better enclosure go lisp.
|
14
bonfy Dec 22, 2017
yield 吧... python generator
|
15
quinoa42 Dec 22, 2017 @julyclyde object 和 closure 分别是 OOP 和 FP 对同一需求的不同实现,只不过现在很多语言同时支持这两种罢了
first class function (或者,按 python 的说法,functions as first class objects )都是需要语言支持 closure 才能实现的 |