+ 2
Python decorator quizz
Hi all, This is one of the question in python challenge, can somebody explain to me output of this programme? def tripler(orig_func): def my_function(orig_val): return(orig_func(orig_val)*3) return(my_function) @tripler def doubler(user_input): return(user_input*2) print(doubler(5)) Out[ ]: 30 Thank you all in advance :)
1 Resposta
+ 2
A decorator function (in this example: tripler) adds extra functionality to any function.
In this case it multiplies the function's result by 3.
The doubler functions is called with parameter 5, this is multiplied by 2, then the decorator applies 10*3 giving the result of 30.
Writing your own decorator might seem difficult at first, but they are terribly useful things. You can read the basics also on sololearn
https://www.sololearn.com/learn/JUMP_LINK__&&__Python__&&__JUMP_LINK/2463/
But to gain a better understanding, I really recommend to read more guides that explain it deeper, for example:
https://realpython.com/primer-on-python-decorators/