简体   繁体   中英

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

I am learning to use decorators and I can't figure out how to pass already defined attributes to the wrapper without making a function specific decorator.

Let's say I have a decorator :

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

    return wrapper

With this I am only able to use it with functions with only defined attributes or without any attribute like :

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

foo1()

But it makes me unable to run :

foo1(1, 2)

With this problem, I also can't use this decorator on different functions that don't have the same amount of attributes to set.

So, it there a way to fix this problem without the use of *args and **kwargs or at least without having to call a function that would look like this : foo((arg1, arg2, argn)) ? Because it would make me unable to define any attribute. This is my only restrain.

Thanks.

The wrapper has to accept arguments (because it replaces the original function bound to the decorated name), and those arguments have to be passed to func .

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

    return wrapper

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM