python基礎 裝飾器

2022-08-12 12:03:12 字數 2451 閱讀 3360

1,裝飾器:

1)為什麼要用裝飾器:因為你開發的程式一旦上市,就要遵守源**開放並且盡量不能修改源**,函式的呼叫方式也盡量不要修改,新的需求來了,每一       款軟體都是需要更新的,在不修改源**,不修改函式呼叫方式,同時還要增加新的功能,怎麼實現呢?所以有了裝飾器,來滿足我們的條件。

2)什麼是裝飾器:顧名思義,裝飾就是修飾,器相當於函式

3)裝飾器定義:其本質就是乙個函式,功能是為其他函式新增新的乙個功能。

2,舉例:

1) 現在來建立乙個最簡單的函式,這組函式值列印「welcome to oldboy」 這個語句

1

defindex():

2print("

welcome to oldboy")

3 index()

2)現在我的需求來了,不能修改源**,不能修改函式呼叫方式,而且還要增加乙個檢視這組函式執行時間的功能,怎麼來實現呢? 這就要用裝飾器了

1

import time #

定義乙個時間模組23

deftimmer(tom):

4def

5 star_time =time.time()#開始時間

6tom()

7 stop_time =time.time()#結束時間

8print("

run time is %s

" %(star_time-stop_time))

9return

1011

12 @timmer #

裝飾器呼叫語法: @呼叫的函式名

13def

index():

14print("

welcome to oldboy")

15 index()

3)這段程式就實現了上述要求,執行結果如下:

welcome to oldboy

run time

is 0.0

4)上面也是無參裝飾器的簡單實現方法

5)有無參裝飾器就有有參裝飾器,有參裝飾器的簡單實現,認證使用者登入,如下

1

defauth1(auth_type):

2def

auth(fuhc):34

if auth_type == "

file":

5 name = input("

please your is name >>>>>:")

6 passwrod = input("

pleale your is passwrod >>>>>>:")

7if name == "

gaoyuan

"and passwrod == "

123":8

print("

hello %s wlecome to here

".center(50,"

-") %(name))

9 res = fuhc(*args, **kwargs)

10return

res11

else:12

print("

bye".center(50,"-"

))13

elif auth_type == "

sql":14

print("

------bye-------")

15return

16return

auth

1718

19 @auth1(auth_type = "

file

") #

index=auth(index)

20def

index():

21print("

you'll feel great

".center(50,"-"

))22

2324 index()

6)輸入正確,執行結果如下

please your is name >>>>>:gaoyuan

pleale your is passwrod >>>>>>:123

-------------hello gaoyuan wlecome to here-------------

----------------you'

ll feel great ----------------

7)輸入錯誤,執行結果如下

please your is name >>>>>:alex

pleale your

is passwrod >>>>>>:123

-----------------------bye------------------------

python基礎 裝飾器

裝飾器本質就是函式,功能是為其他函式新增附加功能。原則 不修改被修飾函式的源 不修改被修飾函式的呼叫方式 裝飾器的知識儲備 裝飾器 高階函式 函式巢狀 閉包 import time 定義乙個裝飾器計算函式執行時間 def timer func start time time.time res fun...

python基礎 裝飾器

裝飾器形成的過程 最簡單的裝飾器 有返回值的 有乙個引數 萬能引數 裝飾器的作用 原則 開放封閉原則 語法糖 裝飾器的固定模式 import time print time.time 獲取當前時間 time.sleep 10 讓程式在執行到這個位置的時候停一會兒 def timmer f 裝飾器函式...

Python基礎 裝飾器

裝飾器是程式開發中經常會用到的乙個功能,程式開發的基礎知識,用好了裝飾器,開發效率如虎添翼,所以這也是python面試中必問的問題,但對於好多初次接觸這個知識的人來講,這個功能有點繞,這個都不會,別跟人家說你會python,看了下面的文章,保證你學會裝飾器。裝飾器 decorator 首先我們需要知...