相关疑难解决方法(0)

在python的Currying装饰员

我正在尝试在python中写一个currying装饰器,我想我已经有了一般的想法,但仍然有一些不正常的情况......

def curry(fun):

    cache = []
    numargs = fun.func_code.co_argcount

    def new_fun(*args, **kwargs):
        print args
        print kwargs
        cache.extend(list(args))

        if len(cache) >= numargs:   # easier to do it explicitly than with exceptions

            temp = []
            for _ in xrange(numargs):
                temp.append(cache.pop())
            fun(*temp)

    return new_fun


@curry
def myfun(a,b):
    print a,b
Run Code Online (Sandbox Code Playgroud)

虽然对于以下情况,这可以正常工作:

myfun(5)
myfun(5)
Run Code Online (Sandbox Code Playgroud)

对于以下情况,它失败:

myfun(6)(7)
Run Code Online (Sandbox Code Playgroud)

任何有关如何正确执行此操作的指示将非常感谢!

谢谢!

python decorator currying

18
推荐指数
3
解决办法
5981
查看次数

Python用任意数量的变量进行curry

我正在尝试使用currying在Python中进行简单的功能添加.我在这里找到了这个咖喱装饰.

def curry(func):     
    def curried(*args, **kwargs):
        if len(args) + len(kwargs) >= func.__code__.co_argcount:
            return func(*args, **kwargs)
        return (lambda *args2, **kwargs2:
            curried(*(args + args2), **dict(kwargs, **kwargs2)))
    return curried

@curry
def foo(a, b, c):
    return a + b + c
Run Code Online (Sandbox Code Playgroud)

现在这很棒,因为我可以做一些简单的讨论:

>>> foo(1)(2, 3)
6
>>> foo(1)(2)(3)
6
Run Code Online (Sandbox Code Playgroud)

但这仅适用于三个变量.如何编写函数foo以便它可以接受任意数量的变量并且仍然可以调整结果?我尝试过使用*args的简单解决方案,但它没有用.

编辑:我已经查看了答案,但仍然无法弄清楚如何编写一个可以执行如下所示的函数:

>>> foo(1)(2, 3)
6
>>> foo(1)(2)(3)
6
>>> foo(1)(2)
3
>>> foo(1)(2)(3)(4)
10
Run Code Online (Sandbox Code Playgroud)

python currying python-2.7

6
推荐指数
1
解决办法
1649
查看次数

标签 统计

currying ×2

python ×2

decorator ×1

python-2.7 ×1