我是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中有没有对应的模式?
发布于 2018-02-22 23:26:02
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)仔细检查了这个属性,以确保该属性是可调用的。
发布于 2018-02-21 19:50:03
这并没有真正的支持。您可以编写如下内容
didSuccess(True) if didSuccess else None在shell中,这看起来像这样:
>>> didSuccess = None
>>> didSuccess(True) if didSuccess else None
>>> didSuccess = lambda b: print("The result is: {}".format(b))
>>> didSuccess(True) if didSuccess else None
The result is: Truehttps://stackoverflow.com/questions/48904773
复制相似问题