簡體   English   中英

在python中僅使用一個裝飾器使用定義的屬性並將n個屬性傳遞給包裝器

[英]Use defined attributes and passing n number of attributes to wrapper using only one decorator in python

我正在學習使用裝飾器,但我無法弄清楚如何在不制作特定於功能的裝飾器的情況下將已定義的屬性傳遞給包裝器。

假設我有一個裝飾器:

def decorator(func):
    def wrapper():
        print("Before the function")
        func()
        print("After the function")

    return wrapper

有了這個,我只能將它與僅具有定義屬性或沒有任何屬性的函數一起使用,例如:

@decorator
def foo1(attribute1=10, attribute2=20):
    print(attribute1, attribute2)
    return

foo1()

但這讓我無法運行:

foo1(1, 2)

對於這個問題,我也不能在沒有相同數量的屬性設置的不同函數上使用這個裝飾器。

那么,有沒有一種方法可以在不使用*args**kwargs情況下解決這個問題,或者至少不必調用如下所示的函數: foo((arg1, arg2, argn)) 因為這會讓我無法定義任何屬性。 這是我唯一的克制。

謝謝。

包裝器必須接受參數(因為它替換了綁定到修飾名稱的原始函數),並且這些參數必須傳遞給func

def decorator(func):
    def wrapper(*args, **kwargs):
        print("Before the function")
        func(*args, **kwargs)
        print("After the function")

    return wrapper

暫無
暫無

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

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