简体   繁体   English

Python function “sum”,语法如下:sum() -> 0 sum(1)(2)(3) -> 6

[英]Python function "sum" with syntax like: sum() -> 0 sum(1)(2)(3) -> 6

I am new to Python and I need to write function sum with similar syntax:我是 Python 的新手,我需要用类似的语法编写 function sum

print(sum())
print(sum(1)(2)(3))
print(sum(1)(2)(3)(-4)(-5))

The output is: output 是:

0
6
-3

I tried to write decorator like this:我试过这样写装饰器:

def sum(a=0):
    res = a
    def helper(b=0):
        nonlocal res
        res += b
        return res
    return helper

But it helps only with fixed quantity of ().但它只对固定数量的 () 有帮助。 So this code works only for: sum(1)(2) -> 3 and doesn't for sum() -> <function sum.<locals>.helper at 0x7fca6de44160> or sum(1)()(3) -> TypeError: 'int' object is not callable I think there should be a decorator with recursion, but i don't know how to realize it所以此代码仅适用于: sum(1)(2) -> 3而不适用于sum() -> <function sum.<locals>.helper at 0x7fca6de44160>sum(1)()(3) - > TypeError: 'int' object is not callable我认为应该有一个递归的装饰器,但我不知道如何实现它

That syntax choice looks very odd to me - should the result of sum(foo) be a number or a function?这种语法选择对我来说看起来很奇怪——sum sum(foo)的结果应该是数字还是 function? The built-in sum just takes an iterable and returns a number, which feels much less surprising.内置的sum只接受一个可迭代对象并返回一个数字,这让人感觉不那么令人惊讶。

However, assuming that you are certain you indeed want to create something that looks like an integer, walks like an integer, swims like an integer but is also callable, the language does let you create it:然而,假设您确定您确实想要创建一个看起来像 integer、走路像 integer、游泳像 integer 但也是可调用的东西,该语言允许您创建它:

class sum(int):
    def __call__(self, x=0):
        return sum(self + x)

The output is as you specified: output 是您指定的:

print(sum())
print(sum(1)(2)(3))
print(sum(1)(2)(3)(-4)(-5))
0
6
-3

Finaly, I found my way of solving this task (using only functions):最后,我找到了解决此任务的方法(仅使用函数):

def sum(x=None):
    value = 0

    def helper(y=None):
        nonlocal value
        if y is None:
            return value
        value += y
        return helper

return helper(x)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM