+ 1
Decorators with multiple input arguments
I've been playing around with Python decorator functions to try and understand how to use them. I've modified the first code example in the course to take multple arguments as follows: def decorator(func, str): def modfunc(): print("============") func(str) print("============") return modfunc def print_text(str): print(str) decorated = decorator(print_text, "Hello World!") decorated() It appears that I can't do this using the @decorator short hand. Is this true or does anyone know how to use this syntax when the decorator takes more than just a single function as an argument?
3 ответов
+ 3
That's not the right way to make/use decorators. Here is a great tutorial: https://youtu.be/FsAPt_9Bf3U
0
A decorator takes a function a returns a function. We typically want the function returned to have the same signature so here is how to do that:
def decor(func):
def wrap(x):
print("#" * len(x) )
func(x)
print("#" * len(x) )
return wrap
decprint = decor(print)
decprint("This is decorating with parameters")
# Here is the second way of wrapping
@decor
def decprint2(x):
print(x)
decprint2("This is also decorating with parameters")
0
Here is an example:
https://code.sololearn.com/cD09ijlIS6Ev/?ref=app