Bird
0
0

Which of the following is the correct way to define an iterator class in Python?

easy📝 Syntax Q12 of 15
Python - Magic Methods and Operator Overloading
Which of the following is the correct way to define an iterator class in Python?
Aclass MyIter: def __next__(self): pass
Bclass MyIter: def next(self): pass
Cclass MyIter: def __iter__(self): return self def __next__(self): pass
Dclass MyIter: def iter(self): return self
Step-by-Step Solution
Solution:
  1. Step 1: Check required methods for iterator

    An iterator class must have __iter__ returning self and __next__ to get next item.
  2. Step 2: Match methods with options

    class MyIter: def __iter__(self): return self def __next__(self): pass correctly defines both __iter__ and __next__ methods.
  3. Final Answer:

    Defines both __iter__ and __next__ methods -> Option C
  4. Quick Check:

    Iterator class needs __iter__ and __next__ [OK]
Quick Trick: Iterator class must have __iter__ and __next__ methods [OK]
Common Mistakes:
  • Using next() instead of __next__()
  • Missing __iter__ method
  • Defining iter() instead of __iter__()

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes