Python中裝飾器的用法

2022-09-06 01:00:15 字數 2474 閱讀 4537

裝飾器的作用

當我們需要為函式拓展新的功能,但是又不能修改函式的內部結構時,就可以通過裝飾器來完成。通過裝飾器為函式拓展功能符合「對於擴充套件是開放的,對於修改是封閉的」這一開閉原則。下面我們將通過六個步驟了解如何使用裝飾器。

步驟一

我們先定義乙個函式f,現在我們需要為其新增執行時列印出當前時間的功能,我們可以通過改變內部**來完成:

def

f():

print('

this is f')

--------------------------------

import

time

deff():

print

(time.time())

print('

this is f')

f()

步驟二

步驟一在函式內部新增列印時間**顯然不符合開閉原則。換種思路,我們可以定義乙個新函式gettime,將f作為引數傳入,執行gettime來實現拓展功能:

import

time

deff():

print('

this is f')

defgettime(func):

print

(time.time())

func()

gettime(f)

步驟三

步驟二中使用gettime確實實現了功能拓展,但是我們的本意是為f函式拓展功能,由呼叫gettime函式來實現顯然不夠友好。讓我們換一種gettime的實現形式:

import

time

defdecorator(func):

def

print

(time.time())

func()

return

deff():

print('

this is f')

d =decorator(f)

d()

步驟四

在步驟三中我們不但需要呼叫新的變數d來實現功能,並且還增加了**的複雜度,可以說甚至不如步驟二中的實現。但是當我們使用了@這個語法糖後情況就將會改變:

import

time

defdecorator(func):

def

print

(time.time())

func()

return

@ decorator

deff():

print('

this is f')

f()

步驟五

在步驟四中我們已經初步實現了裝飾器,但如果f函式是乙個需要傳入引數的函式我們該如何修改:

使用@前:

import

time

defdecorator(func):

def

print

(time.time())

func(n)

return

deff(n):

print('

this is f

' +n)

d =decorator(f)d('

.')

使用@後:

import

time

defdecorator(func):

def

print

(time.time())

func(n)

return

@ decorator

deff(n):

print('

this is f

' +n)f('

.')

步驟六

步驟五中我們實現了只傳入乙個引數的函式裝飾器,那麼如果我們事先不知道被裝飾的函式會有幾個引數我們該怎樣定義裝飾器?這就需要使用如下兩個變長引數:

import

time

defdecorator(func):

print

(time.time())

func(*args, **kwargs)

return

@ decorator

deff(n):

print('

this is f

' +n)

@ decorator

deff2(n,m):

print('

this is f2

' + n +m)f('

.')f2('.

','。

')

Python中裝飾器的用法

定義 裝飾器本身就是乙個函式 為其他函式提供附加功能 不改變源 不改變原呼叫方式 裝飾器 高階函式 巢狀函式 知識點 函式本身就是乙個變數 意味著可以被複製給乙個變數 test test 1 高階函式把函式名當成乙個實參傳遞給另乙個函式func test1 不改變源 的前提下新增 返回值中包含函式名...

python中裝飾器

對修改是封閉的,對擴充套件是開放的 import time def f1 print time.time print this is a function.def f2 print this is a function.print time.time f1 def print current tim...

python中裝飾器的原理及用法

要想理解python中裝飾器的原理首先要明白一下兩點 2 裝飾器的的作用等價於callfucn decfucn callfucn 這兩點在後期的分析中要牢牢的記住。以一段 為例 def decofun func def deco a,b print before callfunc called.fu...