1. 程式人生 > >Day 19 函數之閉包、裝飾器

Day 19 函數之閉包、裝飾器

false print glob src true success 返回值 count please

一、什麽是裝飾器

器即函數
裝飾即修飾,意指為其他函數添加新功能
裝飾器定義:本質就是函數,功能是為其他函數添加新功能

二、裝飾器遵循的原則

1.不修改被裝飾函數的源代碼(開放封閉原則)
2.為被裝飾函數添加新功能後,不修改被修飾函數的調用方式

三、高階函數

高階函數總結
1.函數接收的參數是一個函數名
  作用:在不修改函數源代碼的前提下,為函數添加新功能,
  不足:會改變函數的調用方式
2.函數的返回值是一個函數名
  作用:不修改函數的調用方式
  不足:不能添加新功能

其、程序:

work:

技術分享
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "DaChao" # Date: 2017/6/14 import time import random #一:編寫函數,(函數執行的時間是隨機的) # def work1_ti_work(): # ‘‘‘ # 函數執行的時間是隨機的 # :return: # ‘‘‘ # time.sleep(random.randrange(1,6)) # print("Welcome to my world!") #二:編寫裝飾器,為函數加上統計時間的功能 # def count_time(func):
# ‘‘‘ # 裝飾器功能,增加計算運行時間功能! # :param func: # :return: # ‘‘‘ # def wrapper(): # start_time = time.time() # func() # end_time = time.time() # print("Run time is %s" %(end_time-start_time)) # return wrapper # # @count_time # def work2_ti_work():
# ‘‘‘ # 函數執行時間是隨機的。 # :return: # ‘‘‘ # time.sleep(random.randrange(3,6)) # print("Welcome to my world!") # # work2_ti_work() #三:編寫裝飾器,為函數加上認證的功能 # def check(func): # ‘‘‘ # 修飾器:增加認證功能! # :return: # ‘‘‘ # def wrapper(*args,**kwargs): # usrname = input("Please input your name: ").strip() # echo = input("Please input your echo: ").strip() # if usrname == "dachao" and echo == "123": # print("Login successful!") # func(*args,**kwargs) # else: # print("Login error!") # return wrapper # # @check # def work3_ti_work(usr): # ‘‘‘ # 函數執行時間是隨機的。 # :return: # ‘‘‘ # time.sleep(random.randrange(3,6)) # print("%s,welcome to my world!" %(usr)) # # work3_ti_work("dachao") # 附:雙修飾器增加功能:用戶驗證和登錄時間統計 # def count_time(func): # ‘‘‘ # 裝飾器功能,增加計算運行時間功能! # :param func: # :return: # ‘‘‘ # def wrapper(*args,**kwargs): # start_time = time.time() # func(*args,**kwargs) # end_time = time.time() # print("Run time is %s" %(end_time-start_time)) # return wrapper # # def check(func): # ‘‘‘ # 修飾器:增加認證功能! # :return: # ‘‘‘ # def wrapper(*args,**kwargs): # usrname = input("Please input your name: ").strip() # echo = input("Please input your echo: ").strip() # if usrname == "dachao" and echo == "123": # print("Login successful!") # func(*args,**kwargs) # else: # print("Login error!") # return wrapper # # @count_time #work3_ti_work = count_time(check(work3)) # @check #work3_ti_work = check(work3) # def work3_ti_work(usr): # ‘‘‘ # 函數執行時間是隨機的。 # :return: # ‘‘‘ # time.sleep(random.randrange(3,6)) # print("%s,welcome to my world!" %(usr)) # # work3_ti_work("dachao") #四:編寫裝飾器,為多個函數加上認證的功能(用戶的賬號密碼來源於文件), # 要求登錄成功一次,後續的函數都無需再輸入用戶名和密碼 # 註意:從文件中讀出字符串形式的字典,可以用eval(‘{"name":"egon","password":"123"}‘)轉成字典格式 # a = eval(‘{"name":"egon","password":"123"}‘) # # tag = True # # def count(func): # def wrapper(): # global tag # while tag: # username = input("Please input your name: ").strip() # echo = input("Please input your echo: ").strip() # if username == a["name"] and echo == a["password"]: # tag = False # func() # else: # print("Please input again!") # func() # return wrapper # # @count # def work_1(): # print("111111111111111") # @count # def work_2(): # print("222222222222222") # @count # def work_3(): # print("333333333333333") # # work_1() # work_2() # work_3() #五:編寫下載網頁內容的函數,要求功能是:用戶傳入一個url,函數返回下載頁面的結果 # from urllib.request import urlopen # # def get_url(url): # ‘‘‘ # 從用戶傳入的地址,返回內容 # :return: # ‘‘‘ # res = urlopen(url).read() # return res #六:為題目五編寫裝飾器,實現緩存網頁內容的功能: # 具體:實現下載的頁面存放於文件中, # 如果文件內有值(文件大小不為0),就優先從文件中讀取網頁內容, # 否則,就去下載,然後存到文件中 from urllib.request import urlopen def url_cache(func): def wrapper(*args,**kwargs): print("11111") #測試 f = open("cache1.txt","r") if(f.read() == ""): print("2222") #測試 f.close() #一定記得要關閉文件 f = open("cache1.txt", "wb") f.write(func(*args,**kwargs)) f.close() else: print("3333") #測試 return wrapper @url_cache def get_url(url): ‘‘‘ 從用戶傳入的地址,返回內容 :return: ‘‘‘ res = urlopen(url).read() return res get_url(http://www.baidu.com) #七:還記得我們用函數對象的概念,制作一個函數字典的操作嗎, # 來來來,我們有更高大上的做法,在文件開頭聲明一個空字典,然後在每個函數前加上裝飾器,完成自動添加到字典的操作 # import sys # # func_dic = dict({}) # # def deco(func): # def inner(): # func_dic[func.__name__] = getattr(sys.modules[__name__],func.__name__) # func() # return inner # @deco # def my_append(): # print("My_appeng is running!") # @deco # def my_sss(): # print("My_sss is running!") # # my_append() # my_sss() # print(func_dic) # func_dic["my_append"]()
work

Day 19 函數之閉包、裝飾器