What I have tried:
import import_ipynb
import time
class A:
def func1(self):
for i in range(0, 5):
print(i)
time.sleep(1)
class B:
print('Time is:', A().func1())
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:
Time is: 0 Time is: 1 Time is: 2 Time is: 3 Time is: 4
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:
import time
def func1():
for i in range(0, 5):
yield i
time.sleep(1)
for i in func1():
print(f"Time is: {i}")
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.