如何在python中乘以函数?

时间:2015-05-12 15:16:32

标签: python function monkeypatching function-composition

def sub3(n):
    return n - 3

def square(n):
    return n * n

在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]

不幸的是,当想要将作品用作时,它有点蹩脚:

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

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

>>> square * sub3
TypeError: unsupported operand type(s) for *: 'function' and 'function'

那么,让我们来定义吧!

>>> type(sub3).__mul__ = 'something'
TypeError: can't set attributes of built-in/extension type 'function'

d'哦!

>>> class CoolerFunction(types.FunctionType):
...     pass
...
TypeError: Error when calling the metaclass bases
    type 'function' is not an acceptable base type

d'!哦

class Hack(object):
    def __init__(self, function):
        self.function = function
    def __call__(self, *args, **kwargs):
        return self.function(*args, **kwargs)
    def __mul__(self, other):
        def hack(*args, **kwargs):
            return self.function(other(*args, **kwargs))
        return Hack(hack)
嘿,现在我们到了某个地方......

>>> square = Hack(square)
>>> sub3 = Hack(sub3)
>>> [square(sub3(n)) for n in my_list]
[9, 4, 1, 0, 1, 4, 9, 16, 25, 36]
>>> [(square*sub3)(n) for n in my_list]
[9, 4, 1, 0, 1, 4, 9, 16, 25, 36]
>>> sorted(my_list, key=square*sub3)
[3, 2, 4, 1, 5, 0, 6, 7, 8, 9]

但我不想要一个Hack可驯服的课程!范围规则完全不同于我不完全理解的方式,这甚至比“lameda”更为丑陋。可以说。我想monkeypatch 功能。我怎么能这样做?

4 个答案:

答案 0 :(得分:21)

您可以将hack类用作装饰器,就像它编写的那样,尽管您可能希望为该类选择更合适的名称。

像这样:

class Composable(object):
    def __init__(self, function):
        self.function = function
    def __call__(self, *args, **kwargs):
        return self.function(*args, **kwargs)
    def __mul__(self, other):
        @Composable
        def composed(*args, **kwargs):
            return self.function(other(*args, **kwargs))
        return composed
    def __rmul__(self, other):
        @Composable
        def composed(*args, **kwargs):
            return other(self.function(*args, **kwargs))
        return composed

然后您可以像这样装饰您的功能:

@Composable
def sub3(n):
    return n - 3

@Composable
def square(n):
    return n * n

并按照以下方式撰写:

(square * sub3)(n)

基本上,你使用你的hack类完成了同样的事情,但是将它用作装饰器。

答案 1 :(得分:2)

Python不会(也可能永远不会)在语法层面或作为标准库函数支持函数组合。有各种第三方模块(例如functional)提供了实现函数组合的高阶函数。

答案 2 :(得分:2)

也许是这样的:

class Composition(object):
    def __init__(self, *args):
        self.functions = args

    def __call__(self, arg):
        result = arg
        for f in reversed(self.functions):
            result = f(result)

        return result

然后:

sorted(my_list, key=Composition(square, sub3))

答案 3 :(得分:2)

您可以使用SSPipe library编写函数:

from sspipe import p, px

sub3 = px - 3
square = px * px
composed = sub3 | square
print(5 | composed)