Python 基礎知識 Day4
阿新 • • 發佈:2017-07-04
時間 sleep 本質 ret true 調用 pick 添加 war
本節內容
1 叠代器和裝飾器
2 裝飾器
3 Json 和 Pickle數據序列化
4 軟件目錄結構規範
5 作業:ATM項目開發
一 裝飾器
1 裝飾器:
2 定義:本質是函數,(裝飾其他函數),就是為其他函數添加附加功能
3 原則:
1-不能修改被裝飾的函數的源代碼
2-不能修改被裝飾的函數的調用方式
實現裝飾器知識儲備:
1.函數即"變量" (定義函數體到內存房間,函數體是字符串,調用的時候,通過函數名直接調取內存的函數體,函數名就是內存地址)
2.高階函數
滿足下面兩個條件之一就是高階函數
A:把一個函數名當作實參傳給另一個函數(在不修改被裝飾函數源代碼的情況下為其添加功能)
def bar(): print("in the bar") def test1(func): print(func) func() test1(bar) # 此處bar 就是 把 func = bar ,func等於bar了,意思就是fucn 有了內存地址,有了函數體
import time def bar(): time.sleep(3) 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)) # 這裏就是func 運行的時間 test1(bar)
B:返回值中包含函數名(不修改函數的調用方式)
import time def bar(): time.sleep(3) print("in the bar") def test2(func): print(func) return func bar = (test2(bar)) bar() # 這裏實現了未改變源代碼的情況下,增加打印func(其實就是bar的內存地址)的內存地址的功能 # 並且未改變源函數的調用方式
3.嵌套函數
def foo(): print("in the foo") def bar(): # 函數的嵌套是 在一個函數的函數體內用def 去申明一個函數(而不是調用函數) print("in the bar") bar()
高階函數+嵌套函數 = 裝飾器
__author__ = ‘shellxie‘ # -*- coding:utf-8 -*- import time def timmer(fuc): #未修改源代碼 def warpper (*args,**kwargs): start_time = time.time() fuc() stop_time = time.time() print("in the fuc run time %s"%(stop_time-start_time)) return warpper @timmer #調用裝飾器 def test1(): # 一個被裝飾的函數 time.sleep(3) print("in the test1") test1()
裝飾器1.0版
import time def timer(func): # 這時候timer(test1) 就是tiemr(func) 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") print(timer(test1)) test1= (timer(test1)) test1() # 這時候test1() ------就是執行deco的內存地址然後調用
裝飾器1.0版優化
import time def timer(func): # 這時候timer(test1) 就是tiemr(func) 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 # 這一步的意思就是test1 = timer(test1) def test1(): time.sleep(3) print( "in the test1") # 在不改變調用方式以及源代碼的情況下,給源函數增加功能 @timer def test2(): time.sleep(3) print("in the test2") test1() test2()
Python 基礎知識 Day4