为什么__next __()内部的yield返回生成器对象? [英] Why does a yield from inside __next__() return generator object?

查看:188
本文介绍了为什么__next __()内部的yield返回生成器对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用yield返回类中__next__()函数中的下一个值.但是,它不返回下一个值,而是返回生成器对象.

I am using yield to return the next value in the __next__() function in my class. However it does not return the next value, it returns the generator object.

我试图更好地理解迭代器和yield.我可能做错了方式.

I am trying to better understand iterators and yield. I might be doing it in the wrong way.

看看.

class MyString:
    def __init__(self,s):
        self.s=s

    def __iter__(self):
        return self

    def __next__(self):
        for i in range(len(self.s)):
            yield(self.s[i])

r=MyString("abc")
i=iter(r)
print(next(i))

这将返回:

generator object __next__ at 0x032C05A0

推荐答案

next几乎只是调用__next__().在对象上调用__next__将启动生成器并返回生成器(此时未完成任何操作).

next pretty much just calls __next__() in this case. Calling __next__ on your object will start the generator and return it (no magic is done at this point).

在这种情况下,您可能完全不用定义__next__就可以逃脱:

In this case, you might be able to get away with not defining __next__ at all:

class MyString:
    def __init__(self,s):
        self.s=s

    def __iter__(self):
        for i in range(len(self.s)):
            yield(self.s[i])
        # Or...
        # for item in self.s:
        #     yield item

如果您想使用__iter____next__(以定义迭代器,而不是简单地创建 iterable ),您d可能想做这样的事情:

If you wanted to use __iter__ and __next__ (to define an iterator rather than simply making an iterable), you'd probably want to do something like this:

class MyString:
    def __init__(self,s):
        self.s = s
        self._ix = None

    def __iter__(self):
        return self

    def __next__(self):
        if self._ix is None:
            self._ix = 0

        try:
            item = self.s[self._ix]
        except IndexError:
            # Possibly reset `self._ix`?
            raise StopIteration
        self._ix += 1
        return item

这篇关于为什么__next __()内部的yield返回生成器对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆