在 __iter__ 方法中返回 self 有什么用? [英] What is the use of returning self in the __iter__ method?

查看:91
本文介绍了在 __iter__ 方法中返回 self 有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

def __iter__(self):
    return self 

只是想知道上面的代码一般做了什么,为什么需要.

Just wanted to know what does the above code do in general, why is it required.

我浏览了许多代码教程和代码块,得到了多个没有任何适当规范的答案,只需简要说明就可以了.

I went through many code tutorial and blocks, was getting mutiple answers without any proper specification, just a brief explanation would be great.

推荐答案

for 2.7 而不是 3

for 2.7 instead of 3

这是我的理解

在下面的示例代码中,我们可以说类 Testing 是一个可迭代对象,因为我们使用 __iter__ 实现了它.方法 __iter__ 返回一个迭代器.迭代器使用 next 方法来确定迭代的下一个值.如果我从下面的类中删除 next 方法,代码就会失败.

In below example code, we can say that class Testing is an iterable object because we implemented it with __iter__. Method __iter__ returns an iterator. The iterator uses the next method to determine the next value on the iteration. If I were to remove the next method from the class below, the code would fail.

iterable = 一个可以迭代的对象...用 __iter__

iterable = an object that can be iterated over...implemented with __iter__

iterator = 定义如何迭代的对象...字面上,下一个值是什么.这是通过 __next__

iterator = object that defines how to iterate...literally, what is the next value. This is implemented with __next__

所以你质疑的这段代码实际上接受了类对象(self 是参数)并返回一个迭代器,这使得类对象可迭代.所以在下面的例子中,我们实际上可以遍历类对象 myObj.

So the piece of code you questioned actually takes the class object (self is the argument) and returns an iterator, which makes the class object iterable. So in the example below we can actually iterate over the class object myObj.

class Testing:
    def __init__(self,a,b):
        self.a = a
        self.b = b
    def __iter__ (self):
        return self
    def next(self):
        if self.a <= self.b:
            self.a += 1
            return self.a-1
        else:
            raise StopIteration

myObj = Testing(1,5)           
for i in myObj:
    print i

这篇关于在 __iter__ 方法中返回 self 有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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