自學Python之路-Python基礎+模組+面向物件
自學Python之路-Python網路程式設計自學Python之路-Python併發程式設計+資料庫+前端自學Python之路-django

自學Python4.5 - 裝飾器舉例

舉例1.  編寫裝飾器,為多個函式加上認證的功能(使用者的賬號密碼來源於檔案)
     要求登入成功一次,後續的函式都無需再輸入使用者名稱和密碼

FLAG = False
def login(func):
def inner(*args,**kwargs):
global FLAG
'''登入程式'''
if FLAG:
ret = func(*args, **kwargs) # func是被裝飾的函式
return ret
else:
username = input('username : ')
password = input('password : ')
if username == 'carlos' and password == 'carlos88':
FLAG = True
ret = func(*args,**kwargs) #func是被裝飾的函式
return ret
else:
print('登入失敗')
return inner @login
def shoplist_add():
print('增加一件物品') @login
def shoplist_del():
print('刪除一件物品') shoplist_add()
shoplist_del()

舉例2. 編寫裝飾器,為多個函式加上記錄呼叫功能,要求每次呼叫函式都將被呼叫的函式名稱寫入檔案

def log(func):
def inner(*args,**kwargs):
with open('log','a',encoding='utf-8') as f:
f.write(func.__name__+'\n')
ret = func(*args,**kwargs)
return ret
return inner @log
def shoplist_add():
print('增加一件物品') @log
def shoplist_del():
print('刪除一件物品') shoplist_add()
shoplist_del()
shoplist_del()
shoplist_del()
shoplist_del()
shoplist_del()

3.  編寫下載網頁內容的函式,要求功能是:使用者傳入一個url,函式返回下載頁面的結果

為題目1編寫裝飾器,實現快取網頁內容的功能:

具體:實現下載的頁面存放於檔案中,如果檔案內有值(檔案大小不為0),就優先從檔案中讀取網頁內容,否則,就去下載,然後存到檔案中

import os
from urllib.request import urlopen
def cache(func):
def inner(*args,**kwargs):
if os.path.getsize('web_cache'):
with open('web_cache','rb') as f:
return f.read()
ret = func(*args,**kwargs) #get()
with open('web_cache','wb') as f:
f.write(b'*********'+ret)
return ret
return inner @cache
def get(url):
code = urlopen(url).read()
return code # {'網址':"檔名"}
ret = get('http://www.baidu.com')
print(ret)
ret = get('http://www.baidu.com')
print(ret)
ret = get('http://www.baidu.com')
print(ret)