python学习系列之python装饰器基础(1)


创建装饰器
 
# basic.py

#首先定义一个装饰器auth:

#一般装饰器
def auth(func):
    def inner():
        print 'before'
        func()
        print 'after'
    return inner

#带1个参数的装饰器
def auth_arg(func):
    def inner(arg):
        print 'before'
        func(arg)
        print 'after'
    return inner
     
#带多个参数的装饰器
def auth_args(func):
    def inner(*arg, **kwargs):
        print 'before'
        func(*arg,**kwargs)
        print 'after'
    return inner   

     
@auth
def f1():
    print 'f1'

@auth
def f2():
    print 'f2'

@auth
def f3():
    print 'f3'

#使用带1个参数的装饰器
@auth_arg
def f4(arg):
    print 'f4',arg
     
#使用带多个参数的装饰器   
@auth_args
def f5(arg1,arg2,arg3,arg4):
    print 'f5',arg1,arg2,arg3,arg4

 

 
2.另一个py文件调用这个装饰器
 
#test.py

#coding:utf-8
#!/usr/bin/env python

import basic

basic.f1()
basic.f2()
basic.f3()

#使用带1个参数的装饰器
basic.f4('123')
#使用带多个参数的装饰器
basic.f5('a','b','c','d')

 

3.最后效果:
 
$python test.py

before
f1
after
before
f2
after
before
f3
after
before
f4 123
after
before
f5 a b c d

 

after
4.总结
经过上面几个例子,我们发现,使用动态参数是比较方便万能的,可适用参数不固定的情况,因此该basic.py脚本可以改写为:
 
# basic.py

     
#动态参数的装饰器
def auth(func):
    def inner(*arg, **kwargs):
        print 'before'
        func(*arg,**kwargs)
        print 'after'
    return inner   

     
@auth
def f1():
    print 'f1'

@auth
def f2():
    print 'f2'

@auth
def f3():
    print 'f3'

@auth
def f4(arg):
    print 'f4',arg
     
@auth
def f5(arg1,arg2,arg3,arg4):
    print 'f5',arg1,arg2,arg3,arg4

 

 
 

评论关闭