python decorator

非常好的入门文章:

http://www.cnblogs.com/huxi/archive/2011/03/01/1967600.html

http://coolshell.cn/articles/11265.html

#!/usr/bin/python 

import time
import functools
 
def timeit_0(func):
    start = time.clock()
    func()
    end =time.clock()
    print 'used:', end - start
def timeit_1(func):
    def wrapper():
        start = time.clock()
        func()
        end =time.clock()
        print 'used:', end - start
    return  wrapper

def foo():
    for i in range(0, 100):
        print 'in foo()',i

@timeit_1
def foo_1():
    for i in range(0, 100):
        print 'in foo()',i
"step one--------------------------------------------"
print "timeit_0","#"*10
timeit_0(foo)
"step two--------------------------------------------"
print "timeit_1","#"*10
bar=timeit_1(foo)
bar()
"step three-------------------------------------------"
print "foo 1 with @","#"*10
foo_1()
def timeit(func):
    def wrapper(*args, **kvargs):
        start = time.clock()
        func(*args, **kvargs)
        end =time.clock()
        print 'used:', end - start
    return wrapper
@timeit
def foo(a,b,c,d):
    for i in range(0, a):
        print 'in foo()',i
    for i in range(0, b):
        print 'in foo()',i
    for i in range(0, c):
        print 'in foo()',i
"step four--------------------------------------------"
print "with  *args **kvargs"
foo(10,9,8,7)
print foo.__name__

print """------------------nomally decorate----------------------"""
def dec_0(fun):
    def hello():
        if fun.__doc__==None:
            print fun.__name__,"do not   has doc"
        else:
            print fun.__name__,fun.__doc__
    return hello
@dec_0
def hello_world_0():
    'hello world'
    print "hello"
hello_world_0()
print "#"*5
print hello_world_0.__name__
print "#"*5

print """------------------with arg decorate----------------------"""
def dec_1(sql):
    print sql
    def test(fun):
        def hello():
            if fun.__doc__==None:
                print fun.__name__,"do not   has doc"
            else:
                print fun.__name__,fun.__doc__
        return hello
    return test
@dec_1(sql="test")
def hello_world_1():
    'hello world'
    print "hello"
hello_world_1()
print "#"*5
print hello_world_1.__name__
print "#"*5

print """--------------------with wraps       -----------------"""
from functools import wraps
def dec_2(fun):
    @wraps(fun)
    def hello():
        if fun.__doc__==None:
            print fun.__name__,"do not   has doc"
        else:
            print fun.__name__,fun.__doc__
    return hello
@dec_2
def hello_world_2():
    'hello world'
    print "hello"
hello_world_2()
print "#"*5
print hello_world_2.__name__
print "#"*5

print """------------------with  class-------------------"""
class myDecorator(object):
    def __init__(self, fn):
        print "inside myDecorator.__init__()"
        self.fn = fn
    def __call__(self):
        self.fn()
        print "inside myDecorator.__call__()"
@myDecorator
def aFunction():
    print "inside aFunction()"
aFunction() 



import time
def logger(fn):
    @wraps(fn)
    def wrapper(*args, **kwargs):
        ts = time.time()
        result = fn(*args, **kwargs)
        te = time.time()
        print "function      = {0}".format(fn.__name__)
        print "    arguments = {0} {1}".format(args, kwargs)
        print "    return    = {0}".format(result)
        print "    time      = %.6f sec" % (te-ts)
        return result
    return wrapper
 
@logger
def multipy(x, y):
    return x * y
 
@logger
def sum_num(n):
    s = 0
    for i in xrange(n+1):
        s += i
    return s
 
print multipy(2, 10)
print sum_num(100)
print sum_num(10000000)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值