method chaining in python

前端 未结 4 540
故里飘歌
故里飘歌 2020-12-07 17:56

(not to be confused with itertools.chain)

I was reading the following: http://en.wikipedia.org/wiki/Method_chaining

My question is: what is the best

4条回答
  •  攒了一身酷
    2020-12-07 18:37

    It's possible if you use only pure functions so that methods don't modify self.data directly, but instead return the modified version. You also have to return Chainable instances.

    Here's an example using collection pipelining with lists:

    import itertools
    
    try:
        import builtins
    except ImportError:
        import __builtin__ as builtins
    
    
    class Chainable(object):
        def __init__(self, data, method=None):
            self.data = data
            self.method = method
    
        def __getattr__(self, name):
            try:
                method = getattr(self.data, name)
            except AttributeError:
                try:
                    method = getattr(builtins, name)
                except AttributeError:
                    method = getattr(itertools, name)
    
            return Chainable(self.data, method)
    
        def __call__(self, *args, **kwargs):
            try:
                return Chainable(list(self.method(self.data, *args, **kwargs)))
            except TypeError:
                return Chainable(list(self.method(args[0], self.data, **kwargs)))
    

    Use it like this:

    chainable_list = Chainable([3, 1, 2, 0])
    (chainable_list
        .chain([11,8,6,7,9,4,5])
        .sorted()
        .reversed()
        .ifilter(lambda x: x%2)
        .islice(3)
        .data)
    >> [11, 9, 7]
    

    Note that .chain refers to itertools.chain and not the OP's chain.

提交回复
热议问题