python-3.x - 如何使用运算符来组合函数?

标签 python-3.x python-decorators function-composition

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

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
我想使用运算符进行组合,例如 (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

最佳答案

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

This page (该页面实际上是关于Python operator模块,但命名约定与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)


去测试:
@Composable
def add1(x):
    return x + 1

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

print((add1 @ add2)(5))
# 8

关于python-3.x - 如何使用运算符来组合函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54153527/

相关文章:

clojure - 在 Clojure 中将单参数函数合并为多参数函数

使用 AOP 调用方法前后的 Javascript 控制台输出

python - 为什么 data_received() 没有被调用?

python - 自动递增文件名

在类的所有方法中将参数转换为相同标准的 Pythonic 方式

Python 装饰器覆盖函数参数

haskell - 理解 (>>=) 。 (>>=)

python - 在 Windows 10 上使用 pip 安装 pytorch 时出错

python-3.x - 如何使用 GEKKO 管理模型预测控制应用程序中的采样和命令时间

Python 装饰器 staticmethod 对象不可调用