How to get one value at a time from a generator function in Python?

前端 未结 6 1983
鱼传尺愫
鱼传尺愫 2020-12-24 04:08

Very basic question - how to get one value from a generator in Python?

So far I found I can get one by writing gen.next(). I just want to make sure this

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-24 04:48

    In Python <= 2.5, use gen.next(). This will work for all Python 2.x versions, but not Python 3.x

    In Python >= 2.6, use next(gen). This is a built in function, and is clearer. It will also work in Python 3.

    Both of these end up calling a specially named function, next(), which can be overridden by subclassing. In Python 3, however, this function has been renamed to __next__(), to be consistent with other special functions.

提交回复
热议问题