0
点赞
收藏
分享

微信扫一扫

python 装饰器例子

胡桑_b06e 2023-04-26 阅读 69


1,测试a

#!/usr/bin/env python

def a(fn):
    print 'a>>>>'
    def d(stc):
        print stc+'d>>>>>'
        fn(stc);
    return d

def b(fn):
    def e(args):
        print 'b>>>'
        fn(args)
    return e

@b
@a
def c(st):
    print "dddddd"
    
c('>>c>>')



输出

#!/usr/bin/env python

def a(fn):
    print 'a>>>>'
    def d(stc):
        print stc+'d>>>>>'
        fn(stc);
    return d

def b(fn):
    def e(args):
        print 'b>>>'
        fn(args)
    return e

@b
@a
def c(st):
    print "dddddd"
    
c('>>c>>')



a包-->b包-->b内-->a内-->--c内


2,测试b

import time
 
def timeit(func):
    def wrapper(args):
        start = time.clock()
        func(args)
        end =time.clock()
        print 'used:', end - start
    return wrapper
 
@timeit
def foo(arg):
    print 'in foo(),arg is' + arg
foo("aaaaa")



输出

in foo(),arg isaaaaa
used: 2.37460347614e-05



3,测试c

import time
 
def timeit(s):
    def wrapper1(func):
        print 'sfsdfsddf'
        def wrapper2(args):
            print "the decorator's arg is"+s
            start = time.clock()
            func(args)
            end =time.clock()
            print 'used:', end - start
        return wrapper2
    return wrapper1



输出

sfsdfsddf
the decorator's arg ishello
in foo(),arg isaaaaa
used: 1.87174626943e-05





举报

相关推荐

0 条评论