+ 17

Question concerning Python decorators

In the SL-Python-course there is the example: # begin of code def decor(func): def wrap(): print("============") func() print("============") return wrap @decor def print_text(): print("Hello world!") print_text() # end of code I do not understand, how I would have to change the code to print common strings in the function print_text(). I changed the code into: # begin of code def decor(func,x): def wrap(x): print("============") func(x) print("============") return wrap(x) @decor def print_text(x): print(x) print_text("Hello world!") # end of code This produces errors. Could somebody please correct the second code that I can see how to enter variables in decorators.

2nd Jun 2018, 2:05 PM
Jan Markus
6 Answers
+ 7
I am not familiar with decorators, but this code runs fine. https://code.sololearn.com/cHaWQtg4SE5m/?ref=app
2nd Jun 2018, 2:18 PM
æŽç«‹ćš
+ 6
It's really not that hard, Jan. Just think of this: @dec def func(): pass As this: def func(): pass func = dec(func) ------------------------- All that our decorator function (dec) is doing here is that: 1. It takes in a function 2. It then defines a new function, that calls the first function along with doing other things that add functionality to the first function (in most cases) 3. Finally, it returns the new function. So after applying the decorator, when we call the original function with some arguments, we are really just calling the new (wrap) function with the same arguments. æŽç«‹ćš's answer demonstrates the same. ------------------------- If you're still confused, try this video. It helped me get the concept https://www.youtube.com/watch?v=MYAEv3JoenI Let me know if I can clear anything else up :)
2nd Jun 2018, 3:56 PM
Just A Rather Ridiculously Long Username
3rd Jun 2018, 2:54 AM
woods
+ 1
I accidentally make this code, and I think that it may help in understanding decorators better. https://code.sololearn.com/c7w0aAy4P6sf/?ref=app https://code.sololearn.com/cabFO2TqM1an/?ref=app
6th Jun 2018, 7:05 PM
æŽç«‹ćš
6th Jun 2018, 12:42 PM
Denys Yeromenko
Denys Yeromenko - avatar
0
I think this could help to understand decoration https://code.sololearn.com/cXiJWAB6AhS9/?ref=app
25th May 2019, 2:27 PM
simone
simone - avatar