Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

python - What is the use of returning self in the __iter__ method?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

EDIT: for 2.7 instead of 3

Here is my understanding

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 = an object that can be iterated over...implemented with __iter__

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...