Reputation: 45
def div2(mult):
def display():
print(f"we are doing a check of multiples if div by 2")
if mult%2==0:
return f"{mult} is divisible"
return display
@div2
def multi(n):
return n*n*n
print(multi(5))
In a video i learnt that we need not pass an argument for the wrapped function(display in this e.g), the main function's argument(div2
in this case) will be used in the wrapped function.
When i tried the same for the above code i got a TypeError
that display()
needs a parameter.
Confused now that in this case should all my 3 functions should have the parameters as below:
div2()
-> multi()
function itself as parameter
display()
-> a parameter to display the value of function multi()
multi()
-> a parameter to do the math
Note: When I made display()
take a parameter, the code worked
Upvotes: 0
Views: 38
Reputation: 24058
Here multi takes one parameter, named n
.
def multi(n):
return n*n*n
And using the decorator syntax is actually the same as doing:
multi = div2(multi)
Thus if you want be able to pass paramaters to the wrapper display
it has to be defined to take the parameters.
Upvotes: 0
Reputation: 531420
The problem is not that display
doesn't take an argument; it's that you use it as if it does. Remember that decorator syntax is just syntactic sugar for
def multi(n):
return n*n*n
multi = div2(multi)
The result of div2
isn't required to preserve the signature of div2
's argument, though you have to know if it does or not before you can use that result.
The argument to div2
is a function, not something you can divide by 2. Your decorator should be
def div2(f):
def display(x):
print(f"We are doing a check of multiples if div by 2")
if f(x) % 2 == 0:
return f"{x} is divisible"
return display
@div2
def multi(n):
return n*n*n
prin(multi(5))
Upvotes: 1