0
Decorators in Python. Why doesn't work with two arguments?
Now I am learning decorators in Python and trying to do some practice. With no arguments, just if I want to print sentence, It is alright, decorator works. But if want to try with math, do some addition like example, I've got error message: TypeError: wrap() takes 0 positional arguments but 2 were given. Here is my code on playground https://code.sololearn.com/cd0AA7IGPxBs/#py Can somebody help me, where I did mistake or maybe it is impossible to do at all?
4 Respuestas
+ 5
You have to pass parameters to inner wrap in decorator function and as well as to function you want to decorate , something like this
def apdaila(fn):
def wrap(z,t):
print("^^^^^^^^^^")
fn(z,t)
print("**********")
return wrap
def matem():
print('x + y')
matem()
@apdaila
def sudeti(z,t):
print(z + t)
sudeti(8,9)
But then you can't decorate a different function(talking about matem,because then you will have to provide it arguments as well) without arguments ,
+ 3
maklaudas
May be
return wrap()
In your variant is
return wrap
+ 2
If you use return wrap() you don't need to assign the decor(print_text) to variable and then call it ,it can be called just by printing
decor(print_text)
0
@Petr
as I know and as sample given on this lesson, exactly return wrap should be correct:
def decor(func):
def wrap():
print("============")
func()
print("============")
return wrap
def print_text():
print("Hello world!")
decorated = decor(print_text)
decorated()