+ 5

I'm having troubles with decorators!

Can some explain me using codes with comments? It would help alot!

21st Jul 2017, 1:04 PM
MrCoder
MrCoder - avatar
5 ответов
27th Jul 2017, 6:44 PM
Krafty Coder
Krafty Coder - avatar
+ 4
@Venkatesh Awesome thanks! I get it now, but some parts aren't, a small code example could help! :D
21st Jul 2017, 1:58 PM
MrCoder
MrCoder - avatar
+ 3
Let us say you have a function f doing some task. Now for debugging purposes, you want to print time, state of arguments and what not both before f begins and after f completes. Now also imagine that f is not alone, you have a 1000 similar functions you want to debug. All you want is to add a few print calls at the beginning and end of each f. You can hire an intern for this. Or, you can let Python do all this and spare the poor intern. This is where decorators come in. You write one function d, the decorator. d takes a function, and a list of arguments that the passed function itself takes. Inside, it prints the arguments, time and anything else you ask, and simply calls the function you have provided it. So all d is doing is wrapping f with something. This is a common design pattern. So the developers of Python have made it available through the @d notation. Lisps have had this for decades before Python. Read up with this in mind. Come back with any question.
21st Jul 2017, 1:48 PM
Venkatesh Pitta
Venkatesh Pitta - avatar
0
@MrCoder, please read https://code.sololearn.com/cel81MXmrrp3/?ref=app and let me know if this helps. Admittedly, I have used a class here. Function can be used just as well. Also, this is a minimal example where our function takes no argument. But it cal still be identified by it's properties such as name, doc, and so on. What the @d followed by a function definition does is to create a decorated function object. This, upon evaluation, gives us the output that is seen. Sorry about the late reply. I had unsubscribed after a day or so of silence on this question.
27th Jul 2017, 9:00 PM
Venkatesh Pitta
Venkatesh Pitta - avatar
0
Here is an explanation of the decorator usage: https://code.sololearn.com/cD09ijlIS6Ev/?ref=app
7th Jun 2018, 2:04 AM
Denys Yeromenko
Denys Yeromenko - avatar