首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Swift在python中等效的可选闭包

Swift在python中等效的可选闭包
EN

Stack Overflow用户
提问于 2018-02-21 19:29:44
回答 2查看 179关注 0票数 1

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

在swift中,您可以创建可用作回调可选闭包。下面是一个示例:

代码语言:javascript
复制
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中有没有对应的模式?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-02-22 23:26:02

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

这是我使用的解决方案:

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2018-02-21 19:50:03

这并没有真正的支持。您可以编写如下内容

代码语言:javascript
复制
didSuccess(True) if didSuccess else None

在shell中,这看起来像这样:

代码语言:javascript
复制
>>> 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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48904773

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档