【问题标题】:How to execute a piece of code in a python function after the caller has finished executing?调用者执行完后如何在python函数中执行一段代码?
【发布时间】: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


【解决方案1】:

在您的代码中,print(*func()) 中的*func() 将首先使用生成器func(),这将生成一个列表[0, 1, 2, 3, 4] 并完成JOB

也就是说,print(*func())的形式,func中的JOB必须在print函数开始执行其主体代码之前完成。

所以,在我的选择中,你应该照你说的去做:把 JOB 放到一个新函数中。

【讨论】:

    【解决方案2】:

    尝试执行:print(i, end=" ") 而不是yield i

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多