python裝飾器小計

2021-08-31 03:33:33 字數 1350 閱讀 7970

歡迎光臨我的個人主頁

無引數裝飾器

# coding:utf-8

import time

defdecorator

(func)

:# 向decorator傳入函式名

def(

*args,

**kwargs)

: start = time.time(

) func(

*args,

**kwargs)

total = time.time(

)- start

print

('函式%s的執行時間為:%s秒'

%(func.__name__,total)

)@decorator #相當於 tesla = decorator(tesla)

deftesla

(price=

'95w'):

time.sleep(2)

print

('鷗翼門真帥氣,不過**挺刺激:%s'

% price)

tesla(

)

帶引數裝飾器

# coding:utf-8

import time

defdecorator_para

(count_type)

:def

decorator

(func)

:def

(*args,

**kwargs)

: start = time.time(

) func(

*args,

**kwargs)

total = time.time(

)- start

if count_type ==

'default'

:print

('函式%s的執行時間為:%s秒'

%(func.__name__,total)

)elif count_type ==

'normal'

:print

('函式%s的執行時間為:%.2f秒'

%(func.__name__,total)

) return decorator

@decorator_para(

'normal'

)def

tesla

(price=

'95w'):

time.sleep(2)

print

('鷗翼門真帥氣,不過**挺刺激:%s'

% price)

tesla(

)

python裝飾器 Python 裝飾器

簡言之,python裝飾器就是用於拓展原來函式功能的一種函式,這個函式的特殊之處在於它的返回值也是乙個函式,使用python裝飾器的好處就是在不用更改原函式的 前提下給函式增加新的功能。一般而言,我們要想拓展原來函式 最直接的辦法就是侵入 裡面修改,例如 這是我們最原始的的乙個函式,然後我們試圖記錄...

python裝飾器 裝飾器

由於函式也是乙個物件,而且函式物件可以被賦值給變數,所以,通過變數也能呼叫該函式。def now print 2015 3 25 f now f 2015 3 25 函式物件有乙個 name 屬性,可以拿到函式的名字 now.name now f.name now 現在,假設我們要增強now 函式的...

python裝飾器原理 Python裝飾器原理

裝飾器 decorator 是物件導向設計模式的一種,這種模式的核心思想是在不改變原來核心業務邏輯 的情況下,對函式或類物件進行額外的修飾。python中的裝飾器由python直譯器直接支援,其定義形式如下 decorator def core service 要理解上述 的含義,我們從自定義函式裝...