2014-02-07 4 views
19

Dies ist eine Coroutine, aber Python3.2 sieht es als Generator - warum? Was geht hier vor sich? Ich beziehe mich auf Python Essential Reference von David Beazeley pg: 20.Python-3.2 Coroutine: AttributeError: 'Generator' Objekt hat kein Attribut 'Next'

den entsprechenden Abschnitt zu zitieren:

Normally, functions operate on a single set of input arguments. However, a function can 
also be written to operate as a task that processes a sequence of inputs sent to 
it.This type of function is known as a coroutine and is created by using the yield 
statement as an expression (yield) as shown in this example: 
def print_matches(matchtext): 
    print "Looking for", matchtext 
    while True: 
    line = (yield)  # Get a line of text 
    if matchtext in line: 
     print line 

To use this function, you first call it, advance it to the first (yield), and then 
start sending data to it using send(). For example: 
>>> matcher = print_matches("python") 
>>> matcher.next() # Advance to the first (yield) 
Looking for python 
>>> matcher.send("Hello World") 
>>> matcher.send("python is cool") 
python is cool 
>>> matcher.send("yow!") 
>>> matcher.close() # Done with the matcher function call 

Warum funktioniert mein Code arbeiten - nicht, dass Werke des DB ..

deathstar> python3.2 xxx 
Traceback (most recent call last): 
    File "xxx", line 9, in <module> 
    matcher.next() # Advance to the first (yield) 
AttributeError: 'generator' object has no attribute 'next' 
+4

Duplizieren von http://stackoverflow.com/questions/12274606/theres-no-next-function-in-a-yield-generator-in-python-3 –

Antwort

29

Sie bekommen durch die Fehlermeldung abgeworfen; Typisch macht Python keinen Unterschied - Sie können .send an alles, das yield verwendet, auch wenn es nichts mit dem gesendeten Wert intern tut.

In 3.x ist nicht mehr eine .next-Methode an diese angeschlossen; Verwenden Sie stattdessen die integrierte freie Funktion next.

2

Im Fall, dass Sie finden sich jemand Code Patchen, so scheint es, dass die eingebaute in python3 next() Funktion der nächsten() Funktion des Iterators ruft, so Sie in der Lage sein kann, jemand python2 .next( mit dem suchen/ersetzen python3-tolerable .__next__( wie ich gerade gemacht habe, um Teile des Primefac-Moduls in python3 arbeiten zu lassen (neben anderen trivialen Änderungen).

Hier ist die reference:

next(iterator[, default])

Retrieve the next item from the iterator by calling its next() method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.

0

Für Python-Version 3.2 die Syntax für die next() in-integrierte Funktion matcher.__next__() oder next(matcher) sein sollte.

Verwandte Themen