实现 数据 | 处理一 | 处理二 | 处理三 | 。。。这样的写法,流程清晰,但是不是携程,只是明确数据处理的方式。
class Pipe:
def __init__(self):
self.func = None
def __ror__(self,other):
return self.func(other)
def __call__(self,func):
self.func = func
return self
ror 是or 魔术方法对应的方法,or 就是 a or b ,对管道符左边的a 操作,所以a自带or 方法,函数内的(self,other) 的other就是b,如果a内没有or方法,就会默认找ror方法。ror方法内的(self,other)里的self是b,other就是a,实现向前传导,b内应该实现ror方法。
实现效果就是:
from functools import partial,reduce
from operator import add
pipe = Pipe()
data = [2,3,5,4,]
data|pipe(partial(filter,lambda x:x>2))|pipe(partial(reduce,add))