相关疑难解决方法(0)

Python:定义自己的运算符?

我想定义自己的运算符.python是否支持这样的事情?

python operators

71
推荐指数
6
解决办法
5万
查看次数

如何在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 中的函数组合运算符

这个问题中,我询问了Python中的函数组合运算符。@Philip Tzou提供了以下代码,它可以完成这项工作。

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)

我添加了以下功能。

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

def __gt__(self, other):
    return lambda *args, **kw: self.func(other.func(*args, **kw))
Run Code Online (Sandbox Code Playgroud)

通过这些添加,我们可以使用@*>as 运算符来组成函数。例如,我们可以编写print((add1 @ add2)(5), (add1 * add2)(5), (add1 > add2)(5))并获取# 8 8 8. (PyCharm 抱怨布尔值不可调用(add1 > …

python function-composition python-decorators

7
推荐指数
2
解决办法
5635
查看次数