Função Iterator (iter ()) em Python.
Para dicionário, eu posso usariter()
para iterar sobre as teclas do dicionário.
y = {"x":10, "y":20}
for val in iter(y):
print val
Quando eu tenho o iterador da seguinte maneira,
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
Por que não posso usá-lo dessa maneira
x = Counter(3,8)
for i in x:
print x
nem
x = Counter(3,8)
for i in iter(x):
print x
mas por aqui?
for c in Counter(3, 8):
print c
Qual é o uso deiter()
função?
Eu acho que isso pode ser uma das maneiras de comoiter()
é usado.
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