python裝飾器介紹

"""
裝飾器
定義:本質是函數(器:就是函數的意思),功能:裝飾其餘函數,就是爲其餘函數添加附加功能

原則:
1. 不能修改被裝飾的函數的源代碼
2. 不能修改被裝飾的函數的調用方式

實現裝飾器知識儲備:
1. 函數即"變量"
2. 高階函數
a: 把一個函數名當作實參傳給另外一個函數(在不修改被裝飾函數源代碼的狀況下爲其添加功能)
b: 返回值中包含函數名 (不修改函數的調用方式)
3. 嵌套函數

高階函數 + 嵌套函數 --> 裝飾器

參考連接:http://egon09.blog.51cto.com/9161406/1836763
"""


# 將test1 和 test2 函數添加logging 功能 (未使用使用函數調用)
'''
def logger():
    print ("logging")

def test1():
    pass
    logger()

def test2():
    pass
    logger()

test1()
test2()
'''




# 裝飾器示範_1
'''
import time

def timmer(func):
    def warpper(*args,**kwargs):
        start_time = time.time()
        func()
        stop_time = time.time()
        print ("the func run time is %s"%(stop_time - start_time))
    return warpper

@timmer
def test1():
    time.sleep(3)
    print ("this is test1")

test1()
# this is test1
# the func run time is 3.019197702407837

'''



# 函數即"變量"
# 新概念:函數在內存中以變量形式存放
# 匿名函數沒有函數名,當運行後內存會被立馬回收(def 定義的函數,不會被內存回收,當程序結束後內存地址纔會釋放)
'''
# eg_v1  
def bar():  # 正常運行
    print ("in the bar")
def foo():
    print ("in the foo")
    bar()
foo()
# in the foo
# in the bar


# eg_v2   # 正常運行
def foo():
    print ("in the foo")
    bar()
def bar():
    print ("in the bar")
foo()
# in the foo
# in the bar


# eg_v3  # 拋出異常
def foo():
    print ("in the foo")
    bar()
foo()
def bar():
    print ("in the bar")
# Traceback (most recent call last):
# in the foo
#   File "E:/pycharm-project/PYTHON自動化課程/第二模塊/課堂筆記/裝飾器_v1.py", line 92, in <module>
#     foo()
#   File "E:/pycharm-project/PYTHON自動化課程/第二模塊/課堂筆記/裝飾器_v1.py", line 91, in foo
#     bar()
# NameError: name 'bar' is not defined
'''


# 高階函數
# eg_v1
'''
def bar():
    print ("in the bar")

def test1(func):
    print (func)
# test1(bar)
# # <function bar at 0x0000024DE92E3E18> bar函數的內存地址
'''

# eg_v2
'''
def bar():
    print ("in the bar")

def test1(func):
    print (func)
    func()     # 2 調用func函數時,也運行了bar函數
test1(bar)     # 1 將bar函數傳遞給test1
# <function bar at 0x00000216F49D3E18>
# in the bar
'''


# eg_v3  # 裝飾器第一步(沒有修改源代碼,但改變了調用方式)(test1爲裝飾函數,bar函數爲被裝飾函數)
'''
import time
def bar():
    time.sleep(2)
    print ("in the bar")

def test1(func):
    start_time = time.time()
    func()
    stop_time = time.time()
    print ("the func run time is %s"%(stop_time - start_time))

test1(bar)
# in the bar
# the func run time is 2.000016689300537
'''

# eg_v4

'''
import time
def bar():
    time.sleep(2)
    print("in the bar")

def test2(func):
    print (func)
    return func
# t = test2(bar)  # 將test2(bar) 賦值給t,t() == 調用test2函數,改變了調用方式
# t()
# # <function bar at 0x00000172B2CF3E18>
# # in the bar
bar = test2(bar)    # # 將test2(bar) 賦值給bar,bar() == 調用test2函數,未改變了調用方式
bar()
# <function bar at 0x0000016C6E663E18>
# in the bar
'''

  



# 嵌套函數
# eg_v1
'''
def foo():
    print ("in the foo")
    def bar():
        print ("in the bar")

    bar()
foo()
'''

# eg_v2 # 局部做用域和全局做用域的訪問順序
'''
x = 0
def grandpa():
    x = 1
    def dad():
        x = 2
        def son():
            x = 3
            print (x)
        son()
    dad()
grandpa()
# 3
'''

  





# 寫一個簡單的裝飾器
# eg_v1 不使用語法糖
'''
import time

def timer(func):   # timer(test1) --> func= test1
    def deco():
        start_time = time.time()
        func()   # run test1()
        stop_time = time.time()
        print ("the func run time %s:"%(stop_time - start_time))
    return deco

def test1():
    time.sleep(3)
    print ("in the test1")

def test2():
    time.sleep(3)
    print ("in the test2")
test1 = (timer(test1))  # 賦值必須與被裝飾的函數同名
test1()
# in the test1
# the func run time 3.0068588256835938:
'''


# eg_v2 使用語法糖,不帶參數
'''
import time

def timer(func):   # timer(test1) --> func= test1
    def deco():
        start_time = time.time()
        func()   # run test1()
        stop_time = time.time()
        print ("the func run time %s:"%(stop_time - start_time))
    return deco

@timer
def test1():
    time.sleep(3)
    print ("in the test1")
@timer
def test2():
    time.sleep(3)
    print ("in the test2")

test1()
test2()
# in the test1
# the func run time 3.000098705291748:
# in the test2
# the func run time 3.0001633167266846:
'''



# eg_v2 使用語法糖,被裝飾函數帶參數
'''
import time

def timer(func):   # timer(test1) --> func= test1
    def deco(*args,**kwargs):
        start_time = time.time()
        func(*args,**kwargs)   # run test1()
        stop_time = time.time()
        print ("the func run time %s:"%(stop_time - start_time))
    return deco

@timer
def test1():
    time.sleep(3)
    print ("in the test1")
@timer
def test2(name):   # test2 = timer(test2) == deco test2(name) == deco(name)
    time.sleep(3)
    print ("in the test2",name)

test1()
test2("xieshengsen")
# in the test1
# the func run time 3.0004942417144775:
# in the test2 xieshengsen
# the func run time 3.0003535747528076:
'''



# eg_v3
# 一個簡單的登錄頁面認證過程(裝飾器)(裝飾函數帶參數)
user = "aaaaaa"
pawd = "123456"


def auth(auth_type):
    print ("auth func:",auth_type)
    
    def outer_wrapper(func):
        def wrapper(*args,**kwargs):
            print ("wrapper func args:",*args,**kwargs)

            if auth_type == "local":
                username = input("username:").strip()
                password = input("password:").strip()

                if username == user and password == pawd:
                    print ("login....")
                    res = func(*args,**kwargs)  # from home
                    print ("-*-*-*-*-after auth-*-*-*-*-")
                    return res
                else:
                    print ("invalid...")
            elif auth_type == "ldap":
                input("ldap")
                print ("use ladp auth...")
        return wrapper
    return outer_wrapper


def index():
    print ("welcome to index page.")
    

@auth(auth_type="local")
def home():
    print("welcome to home age.")


@auth(auth_type="ldap")
def bbs():
    print("welcome to bbs age.")

index()
home()
bbs()

  

另 一些關於裝飾器介紹的實例python

來自:http://blog.csdn.net/yhy1271927580/article/details/72758577app

"""
被裝飾的對象爲函數,且不帶參數
簡要說明: @timeit裝飾器對sleep函數進行了裝飾,這是一個裝飾器不帶參數的裝飾器,當sleep函數調用的時候,調用的並非咱們看到的原始的sleep函數,而是裝飾事後的sleep函數。這個裝飾的過程會發生在調用sleep函數以前發生。
裝飾的過程:原生的sleep函數做爲參數傳遞到timeit裝飾器函數的fn參數,經過@wraps這個裝飾器將fn的屬性賦值給底下須要返回的wrap函數,最後返回wrap函數,由此可間,wrap就是裝飾事後的sleep函數了。那麼在調用新sleep函數的時候,就是調用wrap函數,sleep函數的參數2,被wrap函數的*args、**kwargs這兩個可變參數接收。
整個裝飾的目的就是將原生的sleep函數,擴充了一個print(nowTime() - start)的過程。
"""
from time import sleep as sleeping
from time import time as nowtime
from functools import wraps


def timeit(fn):
    @wraps(fn)
    def wrap(*args,**kwargs):
        start = nowtime()
        ret = fn(*args,**kwargs)
        print (nowtime() - start)
        return ret
    return wrap

@timeit
def sleep(n):
    sleeping(n)
    print("sleep time {}s".format(n))
    return n

sleep(2)
print("%s func" % sleep.__name__)
# sleep time 2s
# 2.0028135776519775
# sleep func

  

"""
被裝飾的對象爲函數,且帶參數
簡要說明: @timeit裝飾器對sleep函數進行了裝飾,這是一個裝飾器是帶參數的裝飾器.
這個裝飾器因爲須要傳遞參數,所以須要兩層裝飾,第一層是接受傳遞的參宿,第二層是接收傳遞進來的須要裝飾的函數當sleep函數調用的時候,調用的並非咱們看到的原始的sleep函數,而是裝飾事後的sleep函數。
裝飾的過程:裝飾器第一次接收cpu_time參數,而後返回一個dec裝飾器,而這個dec裝飾器會被再次調用,傳入參數是原生的sleep函數,原生的sleep函數做爲參數傳遞到dec裝飾器函數的fn參數,經過@wraps這個裝飾器將fn的屬性賦值給底下須要返回的wrap函數,最後返回wrap函數
在調用新sleep函數的時候,就是調用wrap函數,sleep函數的參數2,被wrap函數的*args、**kwargs這兩個可變參數接收。整個裝飾的目的就是將原生的sleep函數,擴充了一個time_func = time.clock if cpu_time else time.time和print(nowTime() - start)的過程
"""
from functools import wraps
import time


def timeit(cpu_time=False):
    print("timeit")

    def dec(fn):
        @wraps(fn)
        def wrap(*args,**kwargs):
            start = time.time()
            ret = fn (*args,**kwargs)
            print(time.time() - start)
            return ret
        return wrap
    return dec


@timeit(False)
def sleep(n):
    time.sleep(n)
    print ("time sleep")
    return n

sleep(2)
print("%s func" % sleep.__name__)
# timeit
# time sleep
# 2.009625196456909
# sleep func
相關文章
相關標籤/搜索