【发布时间】:2020-11-06 17:29:10
【问题描述】:
我有一种情况可以这样简化:
def caller(func):
print('''
This is the caller function.
After completing execution of this function, do the JOB(see below)
''')
print(*func())
def my_func():
for i in range(5):
yield i
# JOB:
print('''
This text needs to be printed
after everything from the caller function
(text and numbers both) is printed
''')
caller(my_func)
打印的内容:
This is the caller function. After completing execution of this function, do the JOB(see below) This text needs to be printed after everything from the caller function (text and numbers both) is printed 0 1 2 3 4
我想要什么:
This is the caller function. After completing execution of this function, do the JOB(see below) 0 1 2 3 4 This text needs to be printed after everything from the caller function (text and numbers both) is printed
理论上,我可以将 JOB 放在一个新函数中,并在调用者执行完毕后调用该函数。但我需要在my_func 中创建的变量。此外,它会使我的代码更加混乱。
【问题讨论】:
-
my_func中yield的目的是什么?
*func()将消耗生成器并获取由yield 生成的列表,并且该工作将在打印函数开始处理参数之前完成。所以,我在这里看不到你 my_func 中 yield 的含义。 -
实际上,我有一个对象,我想在 yield 语句的位置返回它的状态。在 JOB 部分,我正在修改对象的状态。因此,在 JOB 完成后我不能拥有
return,因为它最终会返回对象的状态,而不是像在yield语句的位置那样。除了你的答案还有什么想法吗? -
抱歉,没有好主意。
标签: python function functional-programming yield