用隐式类型转换实现逐点算术

时间:2012-12-03 08:21:42

标签: python functional-programming operator-overloading abc python-3.3

假设我有类Function,其实例是带有一个参数的callables。我以直接的方式为这些类定义了逐点算术。这是我的代码的简化版本(我实际上在__init____call__中有更复杂的行为,但这与此问题无关):

class Function:
  '''
  >>> f = Function(lambda x : x**2)
  >>> g = Function(lambda x : x + 4)
  >>> h = f/g
  >>> h(6)
  3.6
  '''
  def __init__(self, func):
    self.func = func
  def __call__(self, value):
    return self.func(value)
  def __truediv__(self, other):
    if isinstance(other, Function):
        return Function(lambda x:self(x)/other(x))
    else:
        return NotImplemented
  # ...

当我尝试允许隐式类型转换时,我陷入困境。例如,我希望能够写:

>>> f = Function(lambda x : x ** 2)
>>> g = f+1
>>> g(5)
26

换句话说,每当我在v实例旁边的算术表达式中看到数字对象Function时,我想将v转换为Function(lambda x : v)

此外,我想为我的一些用户定义的类型实现类似的行为(同样,每当我在带有Function对象的相同二进制算术表达式中看到它们时。

虽然我可以使用强力分类的常规和反射二进制算术运算符来编码这个逻辑,每次检查isinstance(v, numbers.Number)isinstance(v, MyUserDefinedType),我觉得可能有更优雅的方式。

此外,如果我的设计有任何其他改进,请告诉我。 (Function对象很少被创建,但是经常被调用,因此性能会引起一些兴趣。)

编辑:

为了解决@ Eric的评论,我应该澄清我有另一个用户定义的类Functional

class Functional:
  '''
  >>> c = [1, 2, 3]
  >>> f = Functional(lambda x : x + 1)
  >>> f(c)
  [2, 3, 4]
  >>> g = Functional(lambda x : x ** 2)
  >>> h = f + g
  >>> h(c)
  [3, 7, 13]
  '''
  def __init__(self, func):
    self.func = func
  @staticmethod
  def from_function(self, function):
    return Functional(function.func)
  def __call__(self, container):
    return type(container)(self.func(c) for c in container)
  def __add__(self, other):
    if isinstance(other, Functional):
      return Functional(lambda x : self.func(x) + other.func(x))
    else:
      return NotImplemented

当我在同一算术表达式中看到FunctionFunctional实例时,我希望使用FunctionFunctional隐式转换为Functional.from_function方法

因此,隐式类型转换层次结构如下:

  • 功能
  • 功能
  • 其他任何内容

我想隐式转换为在给定算术表达式中看到的此层次结构中的最高类型。

3 个答案:

答案 0 :(得分:2)

对于所有运营商而言,这样的事情会很好:

def __truediv__(self, other):
  if callable(other):
      return Function(lambda x:self(x)/other(x))
  else:
      return Function(lambda x:self(x)/other)

答案 1 :(得分:1)

一个选项是让Function类中的所有运算符都接受任意值,如果它们本身不是函数,它们将应用于基础函数的结果。例如,要扩展允许f / 5,当f是一个函数时,只需修改您必须执行的__truediv__实现:

def __truediv__(self, other):
    if isinstance(other, Function):
        return Function(lambda x:self(x)/other(x))
    else:
        return Function(lambda x:self(x)/other)

你可以选择进行一些类型检查以确保它是理智的(并且提前而不是稍后提出错误),但它没有这个。

答案 2 :(得分:0)

在阅读了评论和其他答案之后,我尝试了这种方法。我发帖要求反馈。我喜欢我可以一举处理FunctionFunctional,但我担心它在性能方面可能会非常昂贵:

class Function:
    '''
    >>> f = Function(lambda x : x**2)
    >>> g = Function(lambda x : x + 4)
    >>> h = f/g
    >>> h(6)
    3.6
    >>> k = f + 1
    >>> k(5)
    26
    >>> m = f + (lambda x : x + 1)
    >>> m(5)
    31
    '''
    def __init__(self, arg):
        if isinstance(arg, Function):
            self.func = arg.func
        elif callable(arg):
            self.func = arg
        else:
            self.func = lambda x : arg
    def __call__(self, value):
        return self.func(value)
    def __truediv__(self, other):
        return self.__class__(lambda x:Function(self)(x)/Function(other)(x))
    def __rtruediv__(self, other):
        return self.__class__(lambda x:Function(other)(x)/Function(self)(x))
    def __add__(self, other):
        return self.__class__(lambda x:Function(self)(x)+Function(other)(x))
    def __radd__(self, other):
        return self.__class__(lambda x:Function(other)(x)+Function(self)(x))
    # ...


class Functional(Function):
    '''
    >>> c = [1, 2, 3]
    >>> f = Functional(lambda x : x + 1)
    >>> f(c)
    [2, 3, 4]
    >>> g = Functional(lambda x : x ** 2)
    >>> h = f + g
    >>> h(c)
    [3, 7, 13]
    '''
    def __call__(self, container):
        return type(container)(self.func(c) for c in container)