码迷,mamicode.com
首页 > 编程语言 > 详细

飘逸的python - 几行代码实现unix管道风格的函数调用

时间:2017-04-18 09:50:12      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:tar   ret   details   调用   .net   ref   other   href   int   

用过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!



飘逸的python - 几行代码实现unix管道风格的函数调用

标签:tar   ret   details   调用   .net   ref   other   href   int   

原文地址:http://www.cnblogs.com/yangykaifa/p/6725990.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!