python裝飾器及warp的作用

2021-10-01 21:01:43 字數 2189 閱讀 8042

首先裝飾器是python乙個很強大的功能,也是動態程式設計的乙個特點。

首先我們知道,在python中乙個函式可以作為引數傳給另外乙個函式:

def hi():

return "hi yasoob!"

def dosomethingbeforehi(func):

print("i am doing some boring work before executing hi()")

print(func())

dosomethingbeforehi(hi)

#outputs:i am doing some boring work before executing hi()

# hi yasoob!

下面裝飾器的用法,就是「裝飾乙個函式」讓這個被裝飾的函式作為裝飾器的引數進行呼叫:

import functools

def itcast1(fun):

# 帶引數的裝飾器

def inner(*args, **kwargs):

print("itcast1 start")

fun(*args, **kwargs)

print("itcast1 end")

return inner

@itcast1

def say_hello():

print('say_hello')

print(say_hello.__name__)

say_hello

>> output: inner

itcast1 start

say_hello

itcast1 end

可以看到,被裝飾之後的函式,就不是函式本身了,名字變成了裝飾器的返回函式,並且是直接呼叫inner函式,所以輸出呼叫的順序就如inner裡面的順序。這樣做可以大大簡化我們的**,將裝飾器的功能寫好,直接裝飾給其他函式就可以了。

接下來看看warp,它作用主要是保持原有函式的名字,doc的屬性。

import functools

def itcast1(fun):

@functools.wraps(fun)

def inner(*args, **kwargs):

print('itcast1 start')

a=fun(*args, **kwargs)

print("itcast1 end")

return inner

@itcast1

def say_hello(a):

print('say_hello')

print(a)

return a

print(say_hello.__name__)

say_hello()

>>output:

say_hello

itcast1 start

say_hello

itcast1 end

從輸出可以看出,函式的名字沒變還是原有函式,而同時繼承了裝飾器內的功能。

如果我們被裝飾的函式有返回值,我們想得到這個返回值,只需要在inner裡返回就可以了。如下:

import functools

def itcast1(fun):

@functools.wraps(fun)

def inner(*args, **kwargs):

print('itcast1 start')

a=fun(*args, **kwargs)

print("itcast1 end")

return a

return inner

@itcast1

def say_hello(a):

print('say_hello')

print(a)

return a

print(say_hello.__name__)

a=say_hello(1)

print(a)

>>output:

say_hello

itcast1 start

say_hello

1itcast1 end

1

詳細看這個:

python裝飾器 Python 裝飾器

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

詳解Python閉包,裝飾器及類裝飾器

在專案開發中,總會遇到在原 的基礎上新增額外的功能模組,原有的 也許是很久以前所寫,為了新增新功能的 塊,您一般還得重新熟悉源 稍微搞清楚一點它的邏輯,這無疑是一件特別頭疼的事情 今天我們介紹的python裝飾器就能夠很好的解決這類問題 閉包函式 閉包比較簡單,直接上 def sum num1 1 ...

詳解Python閉包,裝飾器及類裝飾器

在專案開發中,總會遇到在原 的基礎上新增額外的功能模組,原有的 也許是很久以前所寫,為了新增新功能的 塊,您一般還得重新熟悉源 稍微搞清楚一點它的邏輯,這無疑是一件特別頭疼的事情 今天我們介紹的python裝飾器就能夠很好的解決這類問題 閉包函式 閉包比較簡單,直接上 def sum num1 1 ...