Python自學成才之路 帶有引數的裝飾器

2021-10-08 12:43:31 字數 2509 閱讀 9566

上一節留了點懸念。(

上一節)

函式和裝飾器都可以新增引數,但是裝飾器結構上的區別在於裝飾器是否帶引數。

看下面乙個案例:

class

my_decorate

(object):

def__init__

(self, f)

:"""

如果裝飾器不帶引數,函式需要作為引數傳遞給這個類的構造器

"""print

("進入到 __init__"

) self.f = f

def__call__

(self,

*args)

:print

("進入 __call__"

) self.f(

*args)

print

("結束 __call__"

)@my_decorate

defmyfunction

(arg1, arg2)

:print

('myfunction arguments:'

, arg1, arg2)

print

("開始呼叫myfunction"

)myfunction(

"say"

,"hello"

)myfunction(

"hello"

,"again"

)輸出:

進入到 __init__

開始呼叫myfunction

進入 __call__

myfunction arguments: say hello

結束 __call__

進入 __call__

myfunction arguments: hello again

結束 __call__

mydecorate = my_decorate(myfunction)

mydecorate(

'say'

,'hello'

)mydecorate(

'hello'

,'again'

)

試試列印出myfunction的型別print(type(myfunction)),返回的其實是my_decorate型別,被裝飾器修飾的函式最終型別實際上是裝飾器本身。

裝飾器帶引數後結構發生了較大的變化,這時__init__方法中的引數是裝飾器的引數而不是函式,使用函式作為引數是在__call__方法中,而且__call__方法需要返回可呼叫物件。

class

my_decorate

(object):

def__init__

(self, arg1, arg2, arg3)

:print

("進入 __init__()"

) self.arg1 = arg1

self.arg2 = arg2

self.arg3 = arg3

def__call__

(self, f)

:print

("進入 __call__()"

)def

(*args)

:print()

print

("裝飾器引數:"

, self.arg1, self.arg2, self.arg3)

f(*args)

print

('執行完函式myfunction'

)@my_decorate(

"hello"

,"world",1

)def

myfunction

(*args):if

len(args)

>0:

print

('this is myfunction args: %s'

%str

(args)

)else

:print

('this is myfunctions'

)myfunction(

'hello'

,'myfunction'

)myfunction(

)輸出:

進入 __init__(

)進入 __call__())

裝飾器引數: hello world 1

this is myfunction args:

('hello'

,'myfunction'

)執行完函式myfunction

)裝飾器引數: hello world 1

this is myfunctions

執行完函式myfunction

mydecorate = my_decorate(

"hello"

,"world",1

)'hello'

,'myfunction'

))

python自學成才之路 檔案讀寫操作

python對檔案io操作有兩種格式,第一種是如下形式 filepath iotest.txt try f open filepath,r print f.read finally if f f.close 第二種是如下形式 filepath iotest.txt with open filepat...

Python自學成才之路 什麼是元類

有這麼乙個類 classa object pass a a print type a 輸出 class main a 類a的例項a型別是,如果把type用在類a上會輸出什麼?print type a 輸出 class type 輸出結果,這個type到底是什麼型別,在來看看下面兩個案例。s ads ...

自學成才 總結

前言 這次應該是第五次參加自考了吧,我只想說,自考完之後,乙個字,累。這次總共參加了3科,計算機網路 馬克思,資訊資源管理。1.計算機網路 一直跟著小組的腳步,試卷沒有想象的那麼難,只希望過了吧。2.馬克思主義基本原理概論 oh my god 馬克思貌似是在高中時候學過的吧,已經記不太清了,只知道馬...