#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:zhengzhengliu
#高階函式+巢狀函式==>裝飾器
import time
def timer(func): #timer(test1)-->func=test1
def decor():
start_time = time.time()
func() #run test1
stop_time = time.time()
print("the run time of func is %s" %(stop_time-start_time))
return decor
@timer #test1 = timer(test1)
def test1():
time.sleep(3)
print("in the test1")
@timer #test2 = timer(test2)
def test2():
time.sleep(3)
print("in the test2")
print(timer(test1)) #列印deco的位址
#test1 = timer(test1)
#test2 = timer(test2)
test1() #-->執行decor
test2()
#執行結果:#.decor at 0x00b720c0>
#in the test1
#the run time of func is 3.000171661376953
#in the test2
#the run time of func is 3.000171661376953
1、裝飾器修飾有引數函式
#高階函式+巢狀函式==>裝飾器
import time
def timer(func): #timer(test1)-->func=test1
def decor(arg1,arg2):
start_time = time.time()
func(arg1,arg2) #run test2
stop_time = time.time()
print("the run time of func is %s" %(stop_time-start_time))
return decor
@timer #test2 = timer(test2) = decor test2(name)==>decor(name)
def test2(name,age):
print("test2:",name,age)
test2("liu",23)
#執行結果 :
#test2: liu 23
#the run time of func is 0.0
2、裝飾器修飾多個函式,有的函式帶引數,有大函式不帶引數的情況(採用引數組)
#高階函式+巢狀函式==>裝飾器
import time
def timer(func): #timer(test1)-->func=test1
def decor(*args,**kwargs):
start_time = time.time()
func(*args,**kwargs) #run test1
stop_time = time.time()
print("the run time of func is %s" %(stop_time-start_time))
return decor
@timer #test1 = timer(test1)
def test1():
time.sleep(3)
print("in the test1")
@timer #test2 = timer(test2) = decor test2(name)==>decor(name)
def test2(name,age):
time.sleep(1)
print("test2:",name,age)
#test1 = timer(test1)
#test2 = timer(test2)
test1() #-->執行decor
test2("liu",23)
#執行結果:
#in the test1
#the run time of func is 3.0036065578460693
#test2: liu 23
#the run time of func is 1.0084023475646973
Python3 5 裝飾器及應用詳解(下)
1 裝飾器應用 模擬 登入頁面,訪問需要認證登入頁面 usr bin env python coding utf 8 author zhengzhengliu 模擬 訪問頁面和部分需要登入的頁面 import timer user,passwd liu liu123 def auth func us...
python3 5之mysql擴充套件
最近在學習廖雪峰的python3的教程,這是官方建議大家想學習python的同學可以去看看,真的是在網上能找到的最好文字教程,沒有之一 在廖老實講到使用python3擴充套件mysql這部分的時候,按照原文使用pip install mysql connector python allow exte...
python裝飾器案例
計算函式的執行時間 import requests import time import re 黑名單 def filter url url 過濾url 測試網路請求的響應時間 def check runtime func print 初始裝飾 func.name 判斷url的 path路徑是否存在...