用过linux的基本知道它的管道,是将一个程序或命令的输出作为还有一个程序或命令的输入.

废话少说,以下我们看用python怎么实现unix管道风格的函数调用.

#coding=utf-8
class Pipe:
    def __init__(self, func):
        self.func = func

    def __ror__(self, other):
        return self.func(other)

@Pipe
def add(args):
    return sum(args)

@Pipe
def incr(arg):
    return arg + 1

print [1, 2, 3] | add | incr
原理就是装饰器+操作符重载.(对装饰器一知半解的请看<python装饰器的本质>)
当中魔术方法__ror__重载操作符|
真是简单粗暴.人生苦短,我用python!



相关文章:

  • 2021-09-22
  • 2022-12-23
  • 2021-09-28
  • 2021-06-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-03
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-14
  • 2021-08-13
  • 2022-12-23
  • 2021-12-25
相关资源
相似解决方案