whirlaway
whirlaway

Reputation: 199

How to loop through a class instance?

I was asked this question. Given the code:

class MockList:
    ...code_here...

for i in MockList():
    print(i)

Expected result of for loop:

1 2 3 4 5

How can I do this?

Upvotes: 0

Views: 56

Answers (1)

Stephen Rauch
Stephen Rauch

Reputation: 49812

If you implement an __iter__() method, you can do this functionality:

Code:

class MockList:

    def __iter__(self):
        return iter(range(1, 6))

Test Code:

for i in MockList():
    print(i)

Results:

1
2
3
4
5

Upvotes: 6

Related Questions