作者Freak1033 (金が信念! XD)
看板Python
标题Re: [问题] iterate
时间Fri Jun 1 21:22:53 2007
※ 引述《huggie (huggie)》之铭言:
: 我要我自己做的 class 可以 loop for loop
: for X in Y:
: print X
: 请问那个 Y 要怎麽做?
: 我可以设定一个 Y.foo()
: 让 foo() 变成 generator
: 但如果要直接 loop Y 要如何做呢?
如果你已经有写好的 generator 就称它为 Y.foo 好了, 那你可以这样写:
class Y:
def foo(self):
...
def __iter__(self):
return self.foo()
或者是如果你不想用 generator, 那也可以写自己的 iterator, example:
class fib:
def __init__(self, max = None):
self.max = max
def __iter__(self):
return self.iterator(self)
class iterator:
def __init__(self, owner):
self.a, self.b = 1, 1
self.owner = owner
def next(self):
result, self.a, self.b = self.a, self.b, self.a + self.b
if not self.owner is None and result > self.owner.max:
raise StopIteration
return result
>>> j = fib(200)
>>> for k in j:
print k
1
1
2
3
5
8
13
21
34
55
89
144
>>>
--
その乾いた哀愁の瞳に去来するものは何か?
失ったもの 得たもの
そして广大なネットの狭间で彼が见たものとは?
虚像と实存と记号の中に彼は今、何を想うのか?
<バトルプログラマーシラセ>
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 140.109.224.64
1F:推 huggie:哦..多谢 06/03 02:05