溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Python裝飾器怎么用

發(fā)布時間:2021-10-08 09:59:28 來源:億速云 閱讀:132 作者:小新 欄目:開發(fā)技術

這篇文章給大家分享的是有關Python裝飾器怎么用的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。

裝飾器的基礎使用(裝飾帶參函數)

def decorator(func):
    def inner(info):
        print('inner')
        func(info)
    return inner

@decorator
def show_info(info):
    print(info)

show_info('hello')

防止裝飾器改變裝飾函數名稱

裝飾器在裝飾函數的時候由于返回的是inner的函數地址,所以函數的名稱也會改變 show_info.__name__會變成inner,防止這種現象可以使用functools

import functools

def decorator(func):
	@functools.wraps(func)
    def inner(info):
        print('inner')
        func(info)
    return inner

@decorator
def show_info(info):
    print(info)

show_info('hello')

這樣寫就不會改變被裝飾函數的名稱

裝飾器動態(tài)注冊函數

此方法在Flask框架的app.Route()的源碼中體現

class Commands(object):
    def __init__(self):
        self.cmd = {}

    def regist_cmd(self, name: str) -> None:
        def decorator(func):
            self.cmd[name] = func
            print('func:',func)
            return func
        return decorator

commands = Commands()

# 使得s1的值指向show_h的函數地址
@commands.regist_cmd('s1')
def show_h():
    print('show_h')

# 使得s2的值指向show_e的函數地址
@commands.regist_cmd('s2')
def show_e():
    print('show_e')

func = commands.cmd['s1']
func()

個人心得

在閱讀裝飾器代碼時可以使用加(func_name)的方式
以為例

@commands.regist_cmd('s2')
def show_e():
    print('show_e')

即 show_e = commands.regist_cmd('s2')(show_e)

感謝各位的閱讀!關于“Python裝飾器怎么用”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI