1. 程式人生 > >裝飾器課後練習

裝飾器課後練習

# 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 == 'boss_gold' and password == '22222': # 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()
View Code
# 2.編寫裝飾器,為多個函式加上記錄呼叫功能,要求每次呼叫函式都將被呼叫的函式名稱寫入檔案
def log(func):
    def innner(*args,**kwargs):
        with open(
'log','a',encoding='utf-8') as f: f.write(func.__name__+'\n') ret = func(*args,**kwargs) return ret return innner @log def shoplist_add(): print('增加一件物品') @log def shoplist_del(): print('刪除一件物品') shoplist_add() shoplist_del() shoplist_del() shoplist_del() shoplist_del()
View Code
# 進階作業(選做):
# 1.編寫下載網頁內容的函式,要求功能是:使用者傳入一個url,函式返回下載頁面的結果
# 2.為題目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)
        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)
View Code