Python 2: someIterator.next() vs. next(someIterator) :Python 3

前端 未结 1 372
轮回少年
轮回少年 2021-01-14 06:46

In Python 2 iterators offer .next(), a callable method:

it = iter(xrange(10))
it.next()
> 0
it.next()
> 1
...

In Python

1条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-14 06:58

    You are directly asking about PEP 3114

    consider the following code:

    class test:
        def __iter__(self):
            return self
        def next(self):
            return "next"
        def __next__(self):
            return "__next__"
    
    x = test()
    for i,thing in enumerate(x):
        print(thing)
        if i>4:
            break
    

    in python 2 next is printed but in python 3 __next__ is printed, since the method is being called implicitly it makes way more sense to match other implicit methods such as __add__ or __getitem__, which is described in the PEP.

    If you are planning on using next explicitly then much like len, iter, getattr, hash etc. then python provides a built in function to call the implicit function for you. At least... after PEP 3114.

    0 讨论(0)
提交回复
热议问题