python中裝飾器理解

2022-05-21 09:21:42 字數 4130 閱讀 7288

裝飾器(decorators)是 python 的乙個重要部分。簡單地說:他們是修改其他函式的功能的函式。他們有助於讓我們的**更簡短!

由於函式也是乙個物件,而且函式物件可以被賦值給變數,所以,通過變數也能呼叫該函式。

>>> def now():

... print('2015-3-25')

...>>> f = now

>>> f()

2015-3-25

函式物件有乙個__name__屬性,可以拿到函式的名字:

>>> now.__name__

'now'

>>> f.__name__

'now'

現在,假設我們要增強now()函式的功能,比如,在函式呼叫前後自動列印日誌,但又不希望修改now()函式的定義,這種在**執行期間動態增加功能的方式,稱之為「裝飾器」(decorator)。

本質上,decorator就是乙個返回函式的高階函式。所以,我們要定義乙個能列印日誌的decorator,可以定義如下:

def log(func):

print('call %s():' % func.__name__)

return func(*args, **kw)

觀察上面的log,因為它是乙個decorator,所以接受乙個函式作為引數,並返回乙個函式。我們要借助python的@語法,把decorator置於函式的定義處:

@log

def now():

print('2015-3-25')

呼叫now()函式,不僅會執行now()函式本身,還會在執行now()函式前列印一行日誌:

>>> now()

call now():

2015-3-25

@log放到now()函式的定義處,相當於執行了語句:

now = log(now)

如果decorator本身需要傳入引數,那就需要編寫乙個返回decorator的高階函式,寫出來會更複雜。比如,要自定義log的文字:

def log(text):

def decorator(func):

print('%s %s():' % (text, func.__name__))

return func(*args, **kw)

return decorator

這個3層巢狀的decorator用法如下:

@log('execute')

def now():

print('2015-3-25')

執行結果如下:

>>> now()

execute now():

2015-3-25

和兩層巢狀的decorator相比,3層巢狀的效果是這樣的:

>>> now = log('execute')(now)

>>> now.__name__

import functools

def log(func):

@functools.wraps(func)

print('call %s():' % func.__name__)

return func(*args, **kw)

或者針對帶引數的decorator:

import functools

def log(text):

def decorator(func):

@functools.wraps(func)

print('%s %s():' % (text, func.__name__))

return func(*args, **kw)

return decorator

請編寫乙個decorator,能在函式呼叫的前後列印出'begin call''end call'的日誌。

思考一下能否寫出乙個@log的decorator,使它既支援:

@log

def f():

pass

又支援:

@log('execute')deff():pass

from functools import

wraps

def log(path=''

):

defborder(fun):

@wraps(fun)

result = fun(*args_1, **kwargs)

ifnot

path:

s = '

當前函式名稱為%s,日誌輸出路徑為%s

' % (fun.__name__, './'

)

else

: s = '

當前函式名稱為%s,日誌輸出路徑為%s

' % (fun.__name__

, path)

print

(s)

return

result

return

return

border

@log()

deftest1():

return ("

我是無引數函式")

@log(

'c:\\zhuomian')

deftest2():

return ("

我是無引數函式")

#print(test1())

#print(test2())

@log()

deftest3(name):

return ("

我是有引數函式

",name)

@log(

'c:\\zhuomian')

deftest4(name):

return ("

我是有引數函式

",name)

#print(test3('小王'))

#print(test4('小組'))

class

sg: log()

deftest5(self,name):

return ("

我是例項化函式

",name)

defdecorato(self,fun):

result = fun(*args,**kwargs)

s = '

當前函式名稱為%s,日誌輸出路徑為

' % (fun.__name__

)

return

result

return

#print(sg().test5("例項"))

#選擇例項化函式為裝飾器,sg().decorato

s =sg()

@s.decorato

deftest6(name):

return

name

print(test6("

我怎麼這麼棒

"))

**自:

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中裝飾器的作用

裝飾器的作用就是用乙個新函式封裝舊函式 是舊函式 不變的情況程式設計客棧下增加功能 然後會返回乙個新函式,新函式就叫做裝飾器,一般為了簡化裝飾器會用語法糖 新函式來簡化 例子 這是一段 但功能太少,要對這個進行增強,但又不能改變 def hello return hello world 現在我們的需...

python 中 裝飾器 的作用 與 理解

首先要知道 這個符號 裝飾器,就是個語法糖,主要的作用就是 安全 使用python裝飾器的好處就是在不用更改原函式的 前提下給函式增加新的功能。就是裝飾器的作用,首先介紹下裝飾器 裝飾器就是,假如已經有了乙個函式func a,b 作用是返回a b,但是現在要讓它返回a b的絕對值,就要增加乙個功能,...