欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python裝飾器的兩種使用心得

 更新時間:2021年09月30日 17:22:46   作者:糖烤栗子&  
裝飾器(Decorators)是 Python 的一個重要部分。簡單地說:他們是修改其他函數(shù)的功能的函數(shù)。他們有助于讓我們的代碼更簡短,也更Pythonic(Python范兒),今天通過本文給大家分享Python裝飾器使用小結(jié),感興趣的朋友一起看看吧

裝飾器的基礎(chǔ)使用(裝飾帶參函數(shù))

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

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

show_info('hello')

防止裝飾器改變裝飾函數(shù)名稱

裝飾器在裝飾函數(shù)的時候由于返回的是inner的函數(shù)地址,所以函數(shù)的名稱也會改變 show_info.__name__會變成inner,防止這種現(xiàn)象可以使用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')

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

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

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

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的函數(shù)地址
@commands.regist_cmd('s1')
def show_h():
    print('show_h')

# 使得s2的值指向show_e的函數(shù)地址
@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)

到此這篇關(guān)于Python裝飾器的兩種使用的文章就介紹到這了,更多相關(guān)Python裝飾器使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論