相关疑难解决方法(0)

如何在python中乘以函数?

def sub3(n):
    return n - 3

def square(n):
    return n * n
Run Code Online (Sandbox Code Playgroud)

在python中组合函数很容易:

>>> my_list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> [square(sub3(n)) for n in my_list]
[9, 4, 1, 0, 1, 4, 9, 16, 25, 36]
Run Code Online (Sandbox Code Playgroud)

不幸的是,当想要使用合成作为关键时,它有点蹩脚:

>>> sorted(my_list, key=lambda n: square(sub3(n)))
[3, 2, 4, 1, 5, 0, 6, 7, 8, 9]
Run Code Online (Sandbox Code Playgroud)

这真的应该是sorted(my_list, key=square*sub3),因为heck,函数__mul__不用于其他任何事情:

>>> square * sub3
TypeError: unsupported operand type(s) for *: 'function' and 'function'
Run Code Online (Sandbox Code Playgroud)

好吧,让我们来定义吧!

>>> …
Run Code Online (Sandbox Code Playgroud)

python monkeypatching function function-composition

31
推荐指数
1
解决办法
1762
查看次数

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

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

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)

谢谢。

function-composition python-3.x python-decorators

2
推荐指数
1
解决办法
741
查看次数