天天看點

python學習系列之python裝飾器基礎(1)

首先,提出一個需求:

建立一個裝飾器auth,在不改變原函數的基礎上,在執行的基礎函數f1,f2,f3等幾個函數時候,在f1,f2,f3等原函數的前後增加列印before和after的功能。

  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      
# 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