Code Explanation:
๐น 1. Class Definition
class Test:
✅ Explanation:
A class named Test is created.
Inside this class, a method gen() is defined.
๐น 2. Generator Method Definition
def gen(self):
✅ Explanation:
gen is an instance method.
self refers to the current object.
⚠️ Important:
Because this method contains yield,
it becomes a generator method.
๐น 3. for Loop Inside Generator
for i in range(3):
✅ Explanation:
Loop runs 3 times:
0, 1, 2
๐น 4. yield Statement
yield i
✅ Explanation:
yield returns one value at a time.
After returning value, function pauses.
State is saved for next iteration.
๐น 5. Object Creation
obj = Test()
✅ Explanation:
Creates object obj of class Test.
๐น 6. Calling Generator Method
obj.gen()
✅ Explanation:
Method does NOT execute immediately.
It returns a generator object.
๐น 7. for Loop Iteration
for x in obj.gen():
✅ Explanation:
Python internally calls:
next(generator)
again and again.
๐น 8. First Iteration
๐ Execution:
i = 0
yield 0
✔️ Printed:
0
Function pauses here.
๐น 9. Second Iteration
๐ Execution resumes:
i = 1
yield 1
✔️ Printed:
1
Function pauses again.
๐น 10. Third Iteration
๐ Execution resumes:
i = 2
yield 2
✔️ Printed:
2
๐น 11. Generator Ends
✅ Explanation:
Loop finishes after i = 2
Generator has no more values
Python raises internal:
StopIteration
The for loop automatically handles it and stops.
๐ฏ Final Output
0
1
2

0 Comments:
Post a Comment