gpt4 book ai didi

python - python 中的 Swift 可选闭包等价物

转载 作者:行者123 更新时间:2023-11-28 06:03:21 26 4
gpt4 key购买 nike

我是 Python 新手,在 Objective-C 和 Swift 方面有深厚的背景。

在 swift 中,您可以创建可用作回调的可选闭包。这是一个例子:

class Process {
// The closure that will be assigned by the caller of Process.
var didSuccess: ((Bool)->())?

func run() {
let isSuccess = true
didSuccess?(isSuccess) // If closure is assigned we call it.
}
}


class Robot {
private var process = Process()

init() {
process.didSuccess = examineProcess // We assign the closure
}

func examineProcess(result: Bool) {
print("The result is: \(result)")
}

func run() {
process.run()
}
}

let superPower = SuperPower()
superPower.run()

正如我们所见,当我们调用“superPower.run()”时,输出将是 The result is: true

Python 中是否有等效的模式?

最佳答案

Michael Butscher 发布了一个答案,但我对其进行了改进,因为它可能会导致一些错误。

这是我使用的解决方案:

class Process:
def __init__(self):
self.didSuccess: Callable[[bool], None] = None

def run(self):
if self.didSuccess is not None and callable(self.didSuccess):
# we are sure that we will be able to call didSuccess and avoid bugs
# caused by `myInstance.didSuccess = 3` for example
self.didSuccess(True)

class Robot:
def __init__(self):
self.__process = Process()
self.__process.didSuccess = examineProcess
# or lambda
self.__process.didSuccess = lambda x: print("The result is: ", x)

func examineProcess(bool, result: bool):
print("The result is: ", result)


def run(self):
self.__process.run()

我使用 if self.didSuccess is not None and callable(self.didSuccess) 仔细检查属性以确保该属性是可调用的。

关于python - python 中的 Swift 可选闭包等价物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48904773/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com