Python 中帶參數的裝飾器

在本教程中,我們將討論 Python 中帶有參數的裝飾器,但是在開始這個主題之前,用戶必須學習 Python 中的裝飾器,函數裝飾器。

裝飾器是 Python 中非常強大和有用的工具,因為它允許用戶修改函數或類的行為。

Python 函數可以作為對象被視為至高無上的公民。

  • 函數可以引用變量。
  • 函數可以作為參數傳遞給其他函數。
  • 函數可以從函數中返回。

有參數的裝飾者就像普通的裝飾者。

語法:


@decorator(params)
def function_name():
    '''Function implementation'''

帶參數的裝飾器的代碼實現:


def function_name():
    '''Function implementation'''
function_name = (decorator(params))(function_name)
"""

當我們執行這段代碼時,執行將從左到右開始,這將調用裝飾器(params) 來返回函數對象 func_obj。將使用 func_obj 調用 func_obj(function_name) 。在內部函數中,將執行所需的操作,實際的函數引用將返回分配給函數名。現在,用戶可以使用 function_name() 調用應用了裝飾器的函數。

如何用參數實現裝飾器:

首先,我們將看到如果直接運行參數代碼而不實現任何值,我們可以得到什麼輸出。


def decorators_1(*args, **kwargs):
    def inner_1(func_1):
        '''
           doing operations with func_1
        '''
        return func_1
    return inner_1 # this is the function_object mentioned in the above content

@decorators_1(params)
def func_1():
    """
         function implementation
    """

在上面的代碼中,由於 params 是空的,我們可能會得到一些錯誤。

讓我們逐步了解這一點:


def decorator_function(function_name):
  print("Inside the Decorator: ")

  def inner_1(*args, **kwargs):
    print("Inside the Inner Function: ")
    print("'Decorated the function'")
    # perform this operations with function_name

    function_name()

  return inner_1

@decorator_function
def function_to():
    print("Inside the actual function")

function_to()

輸出:

Inside the Decorator: 
Inside the Inner Function: 
'Decorated the function'
Inside the actual function

代碼執行的可視化表示:

室內裝飾執行:

內部函數執行:

裝飾器功能執行:

最終輸出執行:

在上面的代碼中,我們將從使用帶有參數的裝飾器調用的函數中獲得輸出。

替代方式:

在下面的代碼中,我們將看到如何用另一種方式編寫使用函數裝飾器的代碼。


def decorator_fun(function_name):
  print ("Inside the Decorator: ")

  def inner_1(*args, **kwargs):
    print ("Inside the Inner Function: ")
    print ("'Decorated the function'")
    # Perform this operations with function_name

    function_name()

  return inner_1

def function_to():
    print ("Inside the actual function")

# This is another way of using decorators
decorator_fun(function_to)()

輸出:

Inside the decorator
Inside the inner function
Decorated the function
Inside the actual function

現在,為了更好地理解這個概念,我們將看到使用帶有參數的裝飾的不同示例。

例 1:


def decorator_1(*args, **kwargs):
    print("Inside the Decorator")

    def inner_1(function_1):

        # Here, we will see the functionality of the code:
        print ("Inside the inner function")
        print ("I am studying ", kwargs['JTP'])

        function_1()

    # Returning the inner function   
    return inner_1

@decorator_1(JTP = "COMPUTER SCIENCE AND ENGINEERING ")
def my_function():
    print ("Inside the actual function")

輸出:

Inside the Decorator
Inside the inner function
I am studying COMPUTER SCIENCE AND ENGINEERING 
Inside the actual function

代碼執行的可視化表示:

最終輸出執行:

例 2:


def decorator_function(A, B):

    def Inner_1(function_1):

        def wrapper_1(*args, **kwargs):
            print ("I am studying COMPUTER SCIENCE AND ENGINEERING ")
            print ("Summation of values - {}".format(A + B) )

            function_1(*args, **kwargs)

        return wrapper_1
    return Inner_1

# here, we are not using decorator
def my_function(*args):
    for ele in args:
        print (ele)

# another way of using decorators
decorator_function(22, 14)(my_function)('Computer', 'Science', 'and', 'Engineering')

輸出:

I am studying COMPUTER SCIENCE AND ENGINEERING 
Summation of values - 36
Computer
Science
and
Engineering

上面的例子還顯示了封閉的內部函數可以訪問外部函數的參數。

代碼執行的可視化表示:

例 3:


def deco_decorator(dataType, message_1, message_2):
    def decorator_1(function_1):
        print (message_1)
        def wrapper_1(*args, **kwargs):
            print(message_2)
            if all([type(arg) == dataType for arg in args]):
                return function_1(*args, **kwargs)
            return "Invalid Input"
        return wrapper_1
    return decorator_1

@deco_decorator(str, "Decorator for 'string_Join'", "stringJoin process started ...")
def string_Join(*args):
    st1 = ''
    for K in args:
        st1 += K
    return st1

@deco_decorator(int, "Decorator for 'summation_1'\n", "summation process started ...")
def summation_1(*args):
    summ1 = 0
    for arg in args:
        summ1 += arg
    return summ1

print (string_Join("I ", 'am ', "studying ", 'Computer ', "Science ", "and ", "Engineering"))
print ()
print ("The sum is equal to: ", summation_1(22, 12, 48, 133, 627, 181, 219))

輸出:

Decorator for 'string_Join'
Decorator for 'summation_1'

stringJoin process started ...
I am studying Computer Science and Engineering

summation process started ...
The sum is equal to: 1242

流程的可視化表示:

返回裝飾器 _1:

返回包裝 _1:

執行消息 _1:

執行字符串連接:

執行求和 _1:

最終輸出執行:

結論

在本教程中,我們討論了如何使用帶有參數的裝飾器來執行函數。我們還解釋了使用參數的內部函數和外部函數的可視化表示的例子。


原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/294171.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-26 13:15
下一篇 2024-12-26 13:16

相關推薦

  • Python中引入上一級目錄中函數

    Python中經常需要調用其他文件夾中的模塊或函數,其中一個常見的操作是引入上一級目錄中的函數。在此,我們將從多個角度詳細解釋如何在Python中引入上一級目錄的函數。 一、加入環…

    編程 2025-04-29
  • Python列表中負數的個數

    Python列表是一個有序的集合,可以存儲多個不同類型的元素。而負數是指小於0的整數。在Python列表中,我們想要找到負數的個數,可以通過以下幾個方面進行實現。 一、使用循環遍歷…

    編程 2025-04-29
  • Python周杰倫代碼用法介紹

    本文將從多個方面對Python周杰倫代碼進行詳細的闡述。 一、代碼介紹 from urllib.request import urlopen from bs4 import Bea…

    編程 2025-04-29
  • Python計算陽曆日期對應周幾

    本文介紹如何通過Python計算任意陽曆日期對應周幾。 一、獲取日期 獲取日期可以通過Python內置的模塊datetime實現,示例代碼如下: from datetime imp…

    編程 2025-04-29
  • 如何查看Anaconda中Python路徑

    對Anaconda中Python路徑即conda環境的查看進行詳細的闡述。 一、使用命令行查看 1、在Windows系統中,可以使用命令提示符(cmd)或者Anaconda Pro…

    編程 2025-04-29
  • python強行終止程序快捷鍵

    本文將從多個方面對python強行終止程序快捷鍵進行詳細闡述,並提供相應代碼示例。 一、Ctrl+C快捷鍵 Ctrl+C快捷鍵是在終端中經常用來強行終止運行的程序。當你在終端中運行…

    編程 2025-04-29
  • Python中new和init的區別

    new和init都是Python中常用的魔法方法,它們分別負責對象的創建和初始化,本文將從多個角度詳細闡述它們的區別。 一、創建對象 new方法是用來創建一個對象的,它是一個類級別…

    編程 2025-04-29
  • Python中capitalize函數的使用

    在Python的字符串操作中,capitalize函數常常被用到,這個函數可以使字符串中的第一個單詞首字母大寫,其餘字母小寫。在本文中,我們將從以下幾個方面對capitalize函…

    編程 2025-04-29
  • PHP和Python哪個好找工作?

    PHP和Python都是非常流行的編程語言,它們被廣泛應用於不同領域的開發中。但是,在考慮擇業方向的時候,很多人都會有一個問題:PHP和Python哪個好找工作?這篇文章將從多個方…

    編程 2025-04-29
  • Python for循環求1到100的積

    Python中的for循環可以方便地遍歷列表、元組、字典等數據類型。本文將以Python for循環求1到100的積為中心,從多個方面進行詳細闡述。 一、for循環語法 Pytho…

    編程 2025-04-29

發表回復

登錄後才能評論