python - 什么相当于 Python 中的 Swift 完成 block ?

标签 python swift

在 Swift 中,我们可以编写一个带有完成 block 的函数,如下所示:

func thisNeedsToFinishBeforeWeCanDoTheNextStep(completion: () -> ()) {
    print("The quick brown fox")
    completion()
}

然后当我们调用它时,我们可以在该 block 中放入一些东西,以便在它完成进程后执行:

func thisFunctionNeedsToExecuteSecond() {
   print("jumped over the lazy dog")
}

Python 中的等价物是什么?

最佳答案

Python 将函数视为对象,这意味着您可以传递它们(就像在 Swift 中一样,尽管我不太熟悉 Swift 中的实现细节)。当然,您不能在参数中指定类型,因为您不能用 Python 中的任何内容来指定类型,但这没关系。实现看起来像:

def do_first(completion):
    print("The quick brown fox ")
    completion()

def do_second():
    print("jumped over the lazy dog.")

然后使用它们:

do_first(do_second)

除非您在第一个函数中调用 completion() 之前使用异步代码,否则这些行将按预期顺序执行。

关于python - 什么相当于 Python 中的 Swift 完成 block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38172180/

相关文章:

swift - 如何使用 SpriteKit 创建一堵墙?

ios - 如何使用 SWIFT 4 创建 HMAC MD5 十六进制签名?

python - 在 Python 中将格式打印到文件

python - 将生成器分配给字典直接抛出 StopIteration

python - Python的distutils可以编译.S(汇编)吗?

python - 类型错误 : '<' not supported between instances - objects

ios - Swift:NSTimer 内存泄漏

iOS:在 Interface Builder 中创建具有动态 contentSize 的 UIScrollView

swift - Firebase Auth 与新的 Apple 从社交登录中选择退出

python - 从 df.isnull().sum() 中删除非零字段