且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python中的函数链

更新时间:2022-06-15 09:51:02

我不知道这是 function 链接和 callable 链接一样多,但是,因为函数 可调用的,我想这并没有什么坏处.无论哪种方式,我都可以想到两种方法:

I don't know whether this is function chaining as much as it's callable chaining, but, since functions are callables I guess there's no harm done. Either way, there's two ways I can think of doing this:

第一种方法是使用定义 int 子类="noreferrer">__call__ 返回一个新的自身实例,并带有更新后的值:

The first way would be with a custom int subclass that defines __call__ which returns a new instance of itself with the updated value:

class CustomInt(int):
    def __call__(self, v):
        return CustomInt(self + v)

add 函数现在可以定义为返回一个 CustomInt 实例,该实例作为返回自身更新值的可调用对象,可以连续调用:

Function add can now be defined to return a CustomInt instance, which, as a callable that returns an updated value of itself, can be called in succession:

>>> def add(v):
...    return CustomInt(v)
>>> add(1)
1
>>> add(1)(2)
3
>>> add(1)(2)(3)(44)  # and so on..
50

另外,作为一个int子类,返回值保留了int__repr____str__行为s.但对于更复杂的操作,您应该适当地定义其他 dunders.

In addition, as an int subclass, the returned value retains the __repr__ and __str__ behavior of ints. For more complex operations though, you should define other dunders appropriately.

正如@Caridorc 在评论中指出的那样,add 也可以简单地写成:

As @Caridorc noted in a comment, add could also be simply written as:

add = CustomInt 

将类重命名为 add 而不是 CustomInt 也可以类似地工作.

Renaming the class to add instead of CustomInt also works similarly.

我能想到的唯一其他方法涉及一个嵌套函数,该函数需要一个额外的空参数调用才能返回结果.我使用 nonlocal 并选择将属性附加到函数对象以使其在 Python 之间可移植:

The only other way I can think of involves a nested function that requires an extra empty argument call in order to return the result. I'm not using nonlocal and opt for attaching attributes to the function objects to make it portable between Pythons:

def add(v):
    def _inner_adder(val=None):  
        """ 
        if val is None we return _inner_adder.v 
        else we increment and return ourselves
        """
        if val is None:    
            return _inner_adder.v
        _inner_adder.v += val
        return _inner_adder
    _inner_adder.v = v  # save value
    return _inner_adder 

这会不断返回自身 (_inner_adder),如果提供了 val,则将其递增 (_inner_adder += val),否则, 按原样返回值.就像我提到的,它需要一个额外的 () 调用才能返回递增的值:

This continuously returns itself (_inner_adder) which, if a val is supplied, increments it (_inner_adder += val) and if not, returns the value as it is. Like I mentioned, it requires an extra () call in order to return the incremented value:

>>> add(1)(2)()
3
>>> add(1)(2)(3)()  # and so on..
6