如何使用运算符在 Python 中组合函数?

Rus*_*ott 2 function-composition python-3.x python-decorators

编写一个由其他两个函数组成的函数是相当简单的。(为简单起见,假设它们各有一个参数。)

def compose(f, g):
    fg = lambda x: f(g(x))
    return fg

def add1(x):
    return x + 1

def add2(x):
    return x + 2

print(compose(add1, add2)(5))  # => 8
Run Code Online (Sandbox Code Playgroud)

我想使用运算符进行组合,例如(add1 . add2)(5).

有没有办法做到这一点?

我尝试了各种装饰器配方,但我无法让它们中的任何一个起作用。

def composable(f):
  """
    Nothing I tried worked. I won't clutter up the question 
    with my failed attempts.
  """

@composable
def add1(x):
    return x + 1
Run Code Online (Sandbox Code Playgroud)

谢谢。

Phi*_*zou 6

首先,Python 语法中只允许使用一定数量的运算符符号。点“ .”不是有效的运算符。

这个页面(该页面实际上是关于Pythonoperator模块的,但命名约定与datamodel相同,内容更有条理)列出了所有可用的操作符和相应的实例方法。例如,如果你想使用“ @”作为操作符,你可以像这样写一个装饰器:

import functools

class Composable:

    def __init__(self, func):
        self.func = func
        functools.update_wrapper(self, func)

    def __matmul__(self, other):
        return lambda *args, **kw: self.func(other.func(*args, **kw))

    def __call__(self, *args, **kw):
        return self.func(*args, **kw)

Run Code Online (Sandbox Code Playgroud)

去测试:

@Composable
def add1(x):
    return x + 1

@Composable
def add2(x):
    return x + 2

print((add1 @ add2)(5))
# 8
Run Code Online (Sandbox Code Playgroud)