lambda可以使用* args作为其参数吗? [英] Can lambda work with *args as its parameter?

查看:86
本文介绍了lambda可以使用* args作为其参数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用lambda这样计算总和:

I am calculating a sum using lambda like this:

def my_func(*args):
    return reduce((lambda x, y: x + y), args)

my_func(1,2,3,4)

,其输出为10.

但是我想要一个lambda函数,该函数接受随机参数并将所有参数求和.假设这是一个lambda函数:

But I want a lambda function that takes random arguments and sums all of them. Suppose this is a lambda function:

add = lambda *args://code for adding all of args

某人应该能够将add函数调用为:

someone should be able to call the add function as:

add(5)(10)          # it should output 15
add(1)(15)(20)(4)   # it should output 40

也就是说,一个人应该能够提供任意 括号的数量.

That is, one should be able to supply arbitrary number of parenthesis.

这在Python中可行吗?

Is this possible in Python?

推荐答案

lambda不可能做到这一点,但是使用Python绝对可以做到这一点.

This is not possible with lambda, but it is definitely possible to do this is Python.

要实现此行为,您可以将int子类化并覆盖其__call__方法,以每次返回具有更新值的同一类的新实例:

To achieve this behaviour you can subclass int and override its __call__ method to return a new instance of the same class with updated value each time:

class Add(int):
    def __call__(self, val):
        return type(self)(self + val)

演示:

>>> Add(5)(10)
15
>>> Add(5)(10)(15)
30
>>> Add(5)
5
# Can be used to perform other arithmetic operations as well
>>> Add(5)(10)(15) * 100
3000

如果您也想支持float,则从float而不是int继承子类.

If you want to support floats as well then subclass from float instead of int.

这篇关于lambda可以使用* args作为其参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆