簡體   English   中英

將參數添加到 class 的 python 裝飾器

[英]Add parameter to python decorator of a class

如何將參數name傳遞給調度裝飾器?

import functools

class Dispatcher:
    def dispatch(self, func): # passing name here not worked
        @functools.wraps(func) # passing name here not worked
        def wrapper(*args, **kwargs):
          print('the NAME paramater is:', ???)
        return wrapper


@dispatcher.dispatch(name='foobar')
def send(param):
    pass

send(param='parameter 1')

您的代碼有幾個問題,而且您沒有具體說明您想要什么,但是我想出了一些似乎可以解決您的問題的方法!

import functools
class Dispatcher:

    def dispatch(self, func): # passing name here not worked
        @functools.wraps(func) # passing name here not worked
        def wrapper(*args, **kwargs):
          print('the name paramater is:', kwargs['param'])
        return wrapper

dispatcher = Dispatcher()

@dispatcher.dispatch
def send(param):
    pass

send(param='parameter 1')

我創建了 Dispatcher class 的一個實例,以避免出現所需參數 self 丟失的錯誤。 其次,我沒有調用調度方法,以便它可以將“發送”作為函數。 這就是裝飾器的工作方式。

您向“發送”發送了一個關鍵字參數,所以我使用 kwargs['param'] 訪問它。

我希望我已經幫助了一個兄弟!

您需要將dispatch方法轉換為返回裝飾器的方法。 這允許您在使用參數裝飾 function 時調用它。

import functools


class Dispatcher:

    def dispatch(self, name):
        def decorator(func):
            @functools.wraps(func)
            def wrapper(*args, **kwargs):
                print('Calling decorated function', name)
                func(*args, **kwargs)
                print('Decorated function completed', name)
            return wrapper

        return decorator


dispatcher = Dispatcher()
@dispatcher.dispatch(name='foobar')
def send(param):
    print('Sending with param', param)


send(param='parameter 1')

Output

Calling decorated function foobar
Sending with param parameter 1
Decorated function completed foobar

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM