Chinaunix首页 | 论坛 | 博客
  • 博客访问: 185279
  • 博文数量: 40
  • 博客积分: 1900
  • 博客等级: 上尉
  • 技术积分: 450
  • 用 户 组: 普通用户
  • 注册时间: 2008-07-06 21:31
文章分类
文章存档

2009年(16)

2008年(24)

我的朋友

分类: Python/Ruby

2009-01-13 11:49:48

class ParamError(Exception):
    def __init__(self,args=None):
        self.args=args
        
def ParamDeco(func):
    def DetectParam(*arg):
        if len(arg) > 3:
            raise ParamError("Max 3 params,Supplies {0}".format(len(arg)))
        stop=arg[int(len(arg)/2)] or 0
        step=len(arg)==3 and arg[2] or 1
        start=len(arg) >=2 and arg[0] or 0
        return func(start,stop,step)
    return DetectParam

@ParamDeco
def myRange(start,stop,step):
    i=start
    while i        yield i
        i=i+step
       

for i in myRange(20):
    print(i)

上例是一个使用了yield实现的myRange,通过function deco来实现参数的判定和归属。其中and/or的使用还是比较巧妙的,当然用几个判断也可以实现,代码看起来可能就要冗长一点。
阅读(1049) | 评论(0) | 转发(0) |
0

上一篇:Python generator和yield

下一篇:QT4.5将要LGPL了

给主人留下些什么吧!~~