What I have tried:
JavaScript
x
12
12
1
import import_ipynb
2
import time
3
4
class A:
5
def func1(self):
6
for i in range(0, 5):
7
print(i)
8
time.sleep(1)
9
10
class B:
11
print('Time is:', A().func1())
12
In class B
I want to get print
content in class A
and add 'Time is:'
to the beginning and print it in console. One solution is to return i
as a list at the end of function, but I want i
as instantaneous, not when the function is fully executed. The code I wrote does not do this correctly.
The output I want is:
JavaScript
1
6
1
Time is: 0
2
Time is: 1
3
Time is: 2
4
Time is: 3
5
Time is: 4
6
Advertisement
Answer
Assuming that you don’t want to just change print(i)
to print(f"Time is: {i}")
, you can yield i
from the function, then print at the callsite:
JavaScript
1
10
10
1
import time
2
3
def func1():
4
for i in range(0, 5):
5
yield i
6
time.sleep(1)
7
8
for i in func1():
9
print(f"Time is: {i}")
10
I got rid of the classes since neither was directly relevant to the problem.
yield
turns func1
into a generator function. Calling func1
returns a generator that produces values as needed.