Jest generatorem.next () widoczny w Pythonie 3.0?
Mam generator, który generuje szereg, na przykład:
def triangleNums():
'''generate series of triangle numbers'''
tn = 0
counter = 1
while(True):
tn = tn + counter
yield tn
counter = counter + 1
W Pythonie 2.6 jestem w stanie wykonać następujące wywołania:
g = triangleNums() # get the generator
g.next() # get next val
Jednak w 3.0 jeśli wykonam te same dwie linijki kodu dostaję następujący błąd:
AttributeError: 'generator' object has no attribute 'next'
Ale składnia iteratora pętli działa w 3.0
for n in triangleNums():
if not exitCond:
doSomething...
Nie udało mi się jeszcze znaleźć niczego, co wyjaśniałoby tę różnicę w zachowaniu dla 3.0.
3 answers
Poprawnie, g.next()
został przemianowany na g.__next__()
. Powodem tego jest spójność: specjalne metody, takie jak __init__()
i __del__
, mają podwójne podkreślniki (lub" dunder " w obecnym języku) i .next()
był jednym z niewielu wyjątków od tej reguły. Zostało to naprawione w Pythonie 3.0. [*]
Ale zamiast wywoływać g.__next__()
, Jak mówi Paolo, użyj next(g)
.
[ * ] istnieją inne specjalne atrybuty, które otrzymały tę poprawkę; func_name
, jest teraz __name__
, itp.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-06 05:03:01
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-27 03:52:45
Jeśli Twój kod musi działać pod Python2 i Python3, użyj biblioteki 2to3 six w następujący sposób:
import six
six.next(g) # on PY2K: 'g.next()' and onPY3K: 'next(g)'
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-17 17:09:59