函数关闭与可调用类 [英] Function closure vs. callable class

查看:62
本文介绍了函数关闭与可调用类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在许多情况下,有两种实现选择:闭包和可调用类。例如,

In many cases, there are two implementation choices: a closure and a callable class. For example,

class F:
  def __init__(self, op):
    self.op = op
  def __call__(self, arg1, arg2):
    if (self.op == 'mult'):
      return arg1 * arg2
    if (self.op == 'add'):
      return arg1 + arg2
    raise InvalidOp(op)

f = F('add')

def F(op):
  if op == 'or':
    def f_(arg1, arg2):
      return arg1 | arg2
    return f_
  if op == 'and':
    def g_(arg1, arg2):
      return arg1 & arg2
    return g_
  raise InvalidOp(op)

f = F('add')

在选择一个方向时,应该考虑哪些因素?

What factors should one consider in making the choice, in either direction?

我可以想到两个:


  • 闭包似乎总是会有更好的性能(
    不能想到一个反例)。

  • It seems a closure would always have better performance (can't think of a counterexample).

我认为在某些情况下,关闭无法完成任务(例如,如果
的状态随时间而变化)。

I think there are cases when a closure cannot do the job (e.g., if its state changes over time).

我在这些内容中正确吗?

Am I correct in these? What else could be added?

推荐答案

关闭速度更快。类更灵活(即,可用的方法不仅仅是__call __)。

Closures are faster. Classes are more flexible (i.e. more methods available than just __call__).

这篇关于函数关闭与可调用类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆