Code Explanation;
๐น 1. Class Definition
class Test:
✅ Explanation:
A class Test is created.
It contains a method named gen.
๐น 2. Generator Method Definition
def gen(self):
✅ Explanation:
gen is an instance method.
self refers to the current object.
⚠️ Important:
Since method contains yield,
it becomes a generator method.
๐น 3. Loop Inside Generator
for i in range(3):
✅ Explanation:
Loop runs for:
0, 1, 2
๐น 4. yield Statement
yield i
✅ Explanation:
yield returns one value at a time.
Function pauses after each yield.
State is remembered for next iteration.
๐น 5. Creating Object
obj = Test()
✅ Explanation:
Creates object obj of class Test.
๐น 6. Calling Generator Method
obj.gen()
✅ Explanation:
Does NOT immediately run method.
Returns a generator object.
๐น 7. for Loop Iteration
for x in obj.gen():
✅ Explanation:
Python internally keeps calling:
next(generator)
until generator is exhausted.
๐น 8. First Iteration
๐ Execution:
Loop starts:
i = 0
yield 0
✔️ So:
x = 0
Printed:
0
๐น 9. Second Iteration
๐ Execution:
Generator resumes:
i = 1
yield 1
Printed:
1
๐น 10. Third Iteration
๐ Execution:
Generator resumes:
i = 2
yield 2
Printed:
2
๐น 11. Generator Exhausted
✅ Explanation:
Loop ends after i = 2
No more values
Python raises internal:
StopIteration
which automatically stops loop.
๐ฏ Final Output
0
1
2

0 Comments:
Post a Comment