一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

腳本之家,腳本語言編程技術及教程分享平臺!
分類導航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服務器之家 - 腳本之家 - Python - Python 函數裝飾器詳解

Python 函數裝飾器詳解

2022-02-11 23:05RUNOOB Python

這篇文章主要介紹了Python函數裝飾器,結合實例形式詳細分析了Python裝飾器的原理、功能、分類、常見操作技巧與使用注意事項,需要的朋友可以參考下

裝飾器(Decorators)是 Python 的一個重要部分。簡單地說:他們是修改其他函數的功能的函數。他們有助于讓我們的代碼更簡短,也更Pythonic(Python范兒)。大多數初學者不知道在哪兒使用它們,所以我將要分享下,哪些區域里裝飾器可以讓你的代碼更簡潔。首先,讓我們討論下如何寫你自己的裝飾器。

這可能是最難掌握的概念之一。我們會每次只討論一個步驟,這樣你能完全理解它。

一切皆對象

首先我們來理解下 Python 中的函數:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def hi(name="yasoob"):
    return "hi " + name
print(hi())
# output: 'hi yasoob'
# 我們甚至可以將一個函數賦值給一個變量,比如
greet = hi
# 我們這里沒有在使用小括號,因為我們并不是在調用hi函數
# 而是在將它放在greet變量里頭。我們嘗試運行下這個
print(greet())
# output: 'hi yasoob'
# 如果我們刪掉舊的hi函數,看看會發生什么!
del hi
print(hi())
#outputs: NameError
print(greet())
#outputs: 'hi yasoob'

在函數中定義函數

剛才那些就是函數的基本知識了。我們來讓你的知識更進一步。在 Python 中我們可以在一個函數中定義另一個函數:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def hi(name="yasoob"):
    print("now you are inside the hi() function")
    def greet():
        return "now you are in the greet() function"
    def welcome():
        return "now you are in the welcome() function"
    print(greet())
    print(welcome())
    print("now you are back in the hi() function")
hi()
#output:now you are inside the hi() function
#       now you are in the greet() function
#       now you are in the welcome() function
#       now you are back in the hi() function
# 上面展示了無論何時你調用hi(), greet()和welcome()將會同時被調用。
# 然后greet()和welcome()函數在hi()函數之外是不能訪問的,比如:
greet()
#outputs: NameError: name 'greet' is not defined

那現在我們知道了可以在函數中定義另外的函數。也就是說:我們可以創建嵌套的函數。現在你需要再多學一點,就是函數也能返回函數。

從函數中返回函數

其實并不需要在一個函數里去執行另一個函數,我們也可以將其作為輸出返回出來:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def hi(name="yasoob"):
    def greet():
        return "now you are in the greet() function"
    def welcome():
        return "now you are in the welcome() function"
    if name == "yasoob":
        return greet
    else:
        return welcome
a = hi()
print(a)
#outputs: <function greet at 0x7f2143c01500>
#上面清晰地展示了`a`現在指向到hi()函數中的greet()函數
#現在試試這個
print(a())
#outputs: now you are in the greet() function

再次看看這個代碼。在 if/else 語句中我們返回 greet 和 welcome,而不是 greet() 和 welcome()。為什么那樣?這是因為當你把一對小括號放在后面,這個函數就會執行;然而如果你不放括號在它后面,那它可以被到處傳遞,并且可以賦值給別的變量而不去執行它。你明白了嗎?讓我再稍微多解釋點細節。

當我們寫下 a = hi(),hi() 會被執行,而由于 name 參數默認是 yasoob,所以函數 greet 被返回了。如果我們把語句改為 a = hi(name = "ali"),那么 welcome 函數將被返回。我們還可以打印出 hi()(),這會輸出 now you are in the greet() function

將函數作為參數傳給另一個函數

?
1
2
3
4
5
6
7
8
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!

現在你已經具備所有必需知識,來進一步學習裝飾器真正是什么了。裝飾器讓你在一個函數的前后去執行代碼。

你的第一個裝飾器

在上一個例子里,其實我們已經創建了一個裝飾器!現在我們修改下上一個裝飾器,并編寫一個稍微更有用點的程序:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def a_new_decorator(a_func):
    def wrapTheFunction():
        print("I am doing some boring work before executing a_func()")
        a_func()
        print("I am doing some boring work after executing a_func()")
    return wrapTheFunction
def a_function_requiring_decoration():
    print("I am the function which needs some decoration to remove my foul smell")
a_function_requiring_decoration()
#outputs: "I am the function which needs some decoration to remove my foul smell"
a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)
#now a_function_requiring_decoration is wrapped by wrapTheFunction()
a_function_requiring_decoration()
#outputs:I am doing some boring work before executing a_func()
#        I am the function which needs some decoration to remove my foul smell
#        I am doing some boring work after executing a_func()

你看明白了嗎?我們剛剛應用了之前學習到的原理。這正是 python 中裝飾器做的事情!它們封裝一個函數,并且用這樣或者那樣的方式來修改它的行為。現在你也許疑惑,我們在代碼里并沒有使用 @ 符號?那只是一個簡短的方式來生成一個被裝飾的函數。這里是我們如何使用 @ 來運行之前的代碼:

?
1
2
3
4
5
6
7
8
9
10
11
@a_new_decorator
def a_function_requiring_decoration():
    """Hey you! Decorate me!"""
    print("I am the function which needs some decoration to "
          "remove my foul smell")
a_function_requiring_decoration()
#outputs: I am doing some boring work before executing a_func()
#         I am the function which needs some decoration to remove my foul smell
#         I am doing some boring work after executing a_func()
#the @a_new_decorator is just a short way of saying:
a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)

希望你現在對 Python 裝飾器的工作原理有一個基本的理解。如果我們運行如下代碼會存在一個問題:

?
1
2
print(a_function_requiring_decoration.__name__)
# Output: wrapTheFunction

這并不是我們想要的!Ouput輸出應該是"a_function_requiring_decoration"。這里的函數被warpTheFunction替代了。它重寫了我們函數的名字和注釋文檔(docstring)。幸運的是Python提供給我們一個簡單的函數來解決這個問題,那就是functools.wraps。我們修改上一個例子來使用functools.wraps:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from functools import wraps
def a_new_decorator(a_func):
    @wraps(a_func)
    def wrapTheFunction():
        print("I am doing some boring work before executing a_func()")
        a_func()
        print("I am doing some boring work after executing a_func()")
    return wrapTheFunction
@a_new_decorator
def a_function_requiring_decoration():
    """Hey yo! Decorate me!"""
    print("I am the function which needs some decoration to "
          "remove my foul smell")
print(a_function_requiring_decoration.__name__)
# Output: a_function_requiring_decoration

現在好多了。我們接下來學習裝飾器的一些常用場景。

藍本規范:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from functools import wraps
def decorator_name(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        if not can_run:
            return "Function will not run"
        return f(*args, **kwargs)
    return decorated
@decorator_name
def func():
    return("Function is running")
can_run = True
print(func())
# Output: Function is running
can_run = False
print(func())
# Output: Function will not run

注意:@wraps接受一個函數來進行裝飾,并加入了復制函數名稱、注釋文檔、參數列表等等的功能。這可以讓我們在裝飾器里面訪問在裝飾之前的函數的屬性。

使用場景

現在我們來看一下裝飾器在哪些地方特別耀眼,以及使用它可以讓一些事情管理起來變得更簡單。

授權(Authorization)

裝飾器能有助于檢查某個人是否被授權去使用一個web應用的端點(endpoint)。它們被大量使用于Flask和Django web框架中。這里是一個例子來使用基于裝飾器的授權:

?
1
2
3
4
5
6
7
8
9
from functools import wraps
def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            authenticate()
        return f(*args, **kwargs)
    return decorated

日志(Logging)

日志是裝飾器運用的另一個亮點。這是個例子:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
from functools import wraps
def logit(func):
    @wraps(func)
    def with_logging(*args, **kwargs):
        print(func.__name__ + " was called")
        return func(*args, **kwargs)
    return with_logging
@logit
def addition_func(x):
   """Do some math."""
   return x + x
result = addition_func(4)
# Output: addition_func was called

我敢肯定你已經在思考裝飾器的一個其他聰明用法了。

帶參數的裝飾器

來想想這個問題,難道@wraps不也是個裝飾器嗎?但是,它接收一個參數,就像任何普通的函數能做的那樣。那么,為什么我們不也那樣做呢?這是因為,當你使用@my_decorator語法時,你是在應用一個以單個函數作為參數的一個包裹函數。記住,Python里每個東西都是一個對象,而且這包括函數!記住了這些,我們可以編寫一下能返回一個包裹函數的函數。

在函數中嵌入裝飾器

我們回到日志的例子,并創建一個包裹函數,能讓我們指定一個用于輸出的日志文件:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from functools import wraps
def logit(logfile='out.log'):
    def logging_decorator(func):
        @wraps(func)
        def wrapped_function(*args, **kwargs):
            log_string = func.__name__ + " was called"
            print(log_string)
            # 打開logfile,并寫入內容
            with open(logfile, 'a') as opened_file:
                # 現在將日志打到指定的logfile
                opened_file.write(log_string + '\n')
            return func(*args, **kwargs)
        return wrapped_function
    return logging_decorator
@logit()
def myfunc1():
    pass
myfunc1()
# Output: myfunc1 was called
# 現在一個叫做 out.log 的文件出現了,里面的內容就是上面的字符串
@logit(logfile='func2.log')
def myfunc2():
    pass
myfunc2()
# Output: myfunc2 was called
# 現在一個叫做 func2.log 的文件出現了,里面的內容就是上面的字符串

裝飾器類

現在我們有了能用于正式環境的logit裝飾器,但當我們的應用的某些部分還比較脆弱時,異常也許是需要更緊急關注的事情。比方說有時你只想打日志到一個文件。而有時你想把引起你注意的問題發送到一個email,同時也保留日志,留個記錄。這是一個使用繼承的場景,但目前為止我們只看到過用來構建裝飾器的函數。

幸運的是,類也可以用來構建裝飾器。那我們現在以一個類而不是一個函數的方式,來重新構建logit。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from functools import wraps
class logit(object):
    def __init__(self, logfile='out.log'):
        self.logfile = logfile
    def __call__(self, func):
        @wraps(func)
        def wrapped_function(*args, **kwargs):
            log_string = func.__name__ + " was called"
            print(log_string)
            # 打開logfile并寫入
            with open(self.logfile, 'a') as opened_file:
                # 現在將日志打到指定的文件
                opened_file.write(log_string + '\n')
            # 現在,發送一個通知
            self.notify()
            return func(*args, **kwargs)
        return wrapped_function
    def notify(self):
        # logit只打日志,不做別的
        pass

這個實現有一個附加優勢,在于比嵌套函數的方式更加整潔,而且包裹一個函數還是使用跟以前一樣的語法:

?
1
2
3
@logit()
def myfunc1():
    pass

現在,我們給 logit 創建子類,來添加 email 的功能(雖然 email 這個話題不會在這里展開)。

?
1
2
3
4
5
6
7
8
9
10
11
class email_logit(logit):
    '''
    一個logit的實現版本,可以在函數調用時發送email給管理員
    '''
    def __init__(self, email='[email protected]', *args, **kwargs):
        self.email = email
        super(email_logit, self).__init__(*args, **kwargs)
    def notify(self):
        # 發送一封email到self.email
        # 這里就不做實現了
        pass

從現在起,@email_logit 將會和 @logit 產生同樣的效果,但是在打日志的基礎上,還會多發送一封郵件給管理員。

總結

本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關注服務器之家的更多內容!

原文鏈接:https://www.runoob.com/w3cnote/python-func-decorators.html

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: gayrb免费漫画入口 | 婷婷日日夜夜 | 国产成人在线免费观看 | 久久天天躁狠狠躁夜夜躁 | 国产午夜精品福利 | 国产在线98福利播放视频免费 | 粉嫩极品国产在线观看免费 | 成人精品第一区二区三区 | 青青青青青国产费线在线观看 | 亚洲国产在线99视频 | 精品久久免费观看 | 我不卡影院手机在线观看 | 高清国产在线 | poren黑人 | 免费看片aⅴ免费大片 | 国产高清在线精品一区二区 | ts人妖国产一区 | 日韩精品一区二三区中文 | 日本zzzzwww大片免费 | 99久久999久久久综合精品涩 | 国产香蕉视频在线观看 | 亚洲 欧美 国产 日韩 字幕 | 免费一级日本c片完整版 | 亚洲精品91香蕉综合区 | 美女口述又粗又大感觉 | 高清在线观看mv的网址免费 | 91精品国产91久久久久久 | 3d动漫美女被吸乳羞羞视频 | 久久足恋网 | 性一交一无一伦一精一品 | 亚洲高清中文字幕精品不卡 | chinese调教踩踏视频 | 日韩精品欧美国产精品亚 | 午夜一级毛片看看 | 乳色吐息讲的是什么 | 丰腴尤物贵妇浪荡小说 | 国产农村一一级特黄毛片 | 火影忍者小南裸羞羞漫画 | 精品人伦一区二区三区潘金莲 | 男人搡女人视频免费看 | 日韩性事|