0

Im trying to create a iterator class that will give me a path throw a tree graph, which every iteration it will return the next step according to certain conditions.

So i looked up how to do this here : Build a Basic Python Iterator

and this is what i wrote so far :

def travel_path_iterator(self, article_name):
    return Path_Iter(article_name)


class Path_Iter:

    def __init__(self,article):
        self.article=article

    def __iter__(self):
        return next(self)

    def __next__(self):
        answer= self.article.get_max_out_nb()
        if answer != self.article.get_name():
            return answer
        else:
            raise StopIteration

But I have a problem to call this class. my output is always :

<__main__.Path_Iter object at 0x7fe94049fc50>

any guesses what im doing wrong ?

3
  • 1
    What output? Your code does not output anything. Commented Dec 27, 2015 at 22:35
  • your __next__-method looks weird. Does get_max_out_nb results in the next answer each time called? Commented Dec 27, 2015 at 22:50
  • It would be simpler to write a generator function yielding values. Commented Dec 28, 2015 at 0:42

2 Answers 2

2

While Path_Iter is already an iterator, the __iter__-method should return self:

def __iter__(self):
    return self

Next, to iterate an iterator, you need some kind of loop. E.g. to print the contents, you could convert the iterator to a list:

print list(xyz.travel_path_iterator(article_name))
Sign up to request clarification or add additional context in comments.

3 Comments

i write this in the iterator class or in the function ? there is no need to recursion right ?
where i need to print list(xyz.travel_path_iterator(article_name))? in the PathIter class ?
outside the class, it's an example, how you can use iterators.
0

Using a generator function:

def travel_path_generator(article):
    while True:
        answer = article.get_max_out_nb()
        if answer == article.get_name()
            break
        else:
            yield answer

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.