wenn ich eine Klasse haben möchte, die als Iterator verwendet werden kann (sagt man das so?), was brauche ich dann?
Ganz von Anfang an:
Code: Alles auswählen
def itera():
yield "1"
yield "2"
i = itera()
print i
print i.next()
print i.next()
print i.next()
Code: Alles auswählen
<generator object at 0x00C070A8>
1
2
Traceback (most recent call last):
File "Generator.py", line 22, in <module>
print i.next()
StopIteration
http://www.python-forum.de/topic-16879. ... =generator
Aber das hilft mir nicht recht weiter. Wie benutze ich das Ding? Ich glaube verstanden zu haben, daß die Verwendung von "yield" implizit eine Methode next() liefert und daß die Verwendung von __iter__() die Klasse zu einem Generator macht. Offensichtlich ist das nicht so:
Code: Alles auswählen
class isIter( object):
def __iter__( self):
yield "1"
yield "2"
i = isIter()
print i
print i.next()
print i.next()
print i.next()
Code: Alles auswählen
<__main__.isIter object at 0x00C03070>
Traceback (most recent call last):
File "Generator.py", line 25, in <module>
print i.next()
AttributeError: 'isIter' object has no attribute 'next'
Code: Alles auswählen
class isIter( object):
def next( self):
yield "1"
yield "2"
i = isIter()
print i
print i.next()
print i.next()
print i.next()
Code: Alles auswählen
<__main__.isIter object at 0x00C04070>
<bound method isIter.next of <__main__.isIter object at 0x00C04070>>
<generator object at 0x00BEBEE0>
<generator object at 0x00BEBEE0>
<generator object at 0x00BEBEE0>
Code: Alles auswählen
def class ....
....
def __iter__(self):
return self
....
Gruß und Danke,
Christoph