对于字典,我可以使用iter()
用于迭代字典的键。
y = {"x":10, "y":20}
for val in iter(y):
print val
当我有如下迭代器时,
class Counter:
def __init__(self, low, high):
self.current = low
self.high = high
def __iter__(self):
return self
def next(self):
if self.current > self.high:
raise StopIteration
else:
self.current += 1
return self.current - 1
为什么我不能这样使用
x = Counter(3,8)
for i in x:
print x
nor
x = Counter(3,8)
for i in iter(x):
print x
但这样呢?
for c in Counter(3, 8):
print c
有什么用iter()
功能?
ADDED
我想这可能是方法之一iter()
用来。
class Counter:
def __init__(self, low, high):
self.current = low
self.high = high
def __iter__(self):
return self
def next(self):
if self.current > self.high:
raise StopIteration
else:
self.current += 1
return self.current - 1
class Hello:
def __iter__(self):
return Counter(10,20)
x = iter(Hello())
for i in x:
print i