python中的Swift可选闭包等价物

时间:2018-02-21 11:29:44

标签: python swift callback closures

我是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中是否存在等效模式?

2 个答案:

答案 0 :(得分:1)

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)仔细检查属性,以确保该属性可以调用。

答案 1 :(得分:0)

对此没有真正的支持。你可以写点像

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: True