简体   繁体   English

python中的Swift可选闭包等效

[英]Swift optional closure equivalent in python

I'm new in Python with a strong background in Objective-C and Swift.我是 Python 新手,拥有丰富的 Objective-C 和 Swift 背景。

In swift you can create optional closures that could be use as callback.在 swift 中,您可以创建可用作回调的可选闭包。 Here is a example:下面是一个例子:

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()

As we can see when we will call 'superPower.run()' the output will be The result is: true正如我们所看到的,当我们调用 'superPower.run()' 时,输出将是The result is: true

Is there an equivalent pattern in Python? Python 中是否有等效的模式?

Michael Butscher posted an answer but I improved it because it could lead to some bugs. Michael Butscher 发布了一个答案,但我对其进行了改进,因为它可能会导致一些错误。

This is the solution I use:这是我使用的解决方案:

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()

I do double check on the attribute with if self.didSuccess is not None and callable(self.didSuccess) to be sure that the attribute is callable.我使用if self.didSuccess is not None and callable(self.didSuccess)对属性进行双重检查,以确保该属性是可调用的。

There is no real support for this.对此没有真正的支持。 You can write something like你可以写类似的东西

didSuccess(True) if didSuccess else None

In the shell this looks like:在外壳中,这看起来像:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM