A function composition operator in Python

后端 未结 3 1086
孤独总比滥情好
孤独总比滥情好 2021-01-21 03:27

In this question I asked about a function composition operator in Python. @Philip Tzou offered the following code, which does the job.

import functools

class Co         


        
3条回答
  •  梦毁少年i
    2021-01-21 03:49

    I am actually unwilling to provide this answer. But you should know in certain circumstance you can use a dot "." notation even it is a primary. This solution only works for functions that can be access from globals():

    import functools
    
    class Composable:
    
        def __init__(self, func):
            self.func = func
            functools.update_wrapper(self, func)
    
        def __getattr__(self, othername):
            other = globals()[othername]
            return lambda *args, **kw: self.func(other.func(*args, **kw))
    
        def __call__(self, *args, **kw):
            return self.func(*args, **kw)
    
    

    To test:

    @Composable
    def add1(x):
        return x + 1
    
    @Composable
    def add2(x):
        return x + 2
    
    print((add1.add2)(5))
    # 8
    

提交回复
热议问题