我是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/