+ 2

How can i know where to use decorators? And why to use them?

it seems without decorators the code can run correctly :|

15th Mar 2018, 9:04 AM
Majid Ostovari
Majid Ostovari - avatar
9 Antworten
+ 6
Python decorators allow you to extend the functionality of a function without touching it, let's take the following example: def func(): print("Hello") We need our function to execute some code before calling it and after calling it, let's see: def func(): print("====") print("Hello") print("====") outputs: ==== hello ==== Well, that worked, but sometimes that is not possible you might be unable to change the function, it may be written by other programmers, so the decorator is your solution, let's try now. #decorator takes a function as it's argument def decorator(func): def wrap(): #code to execute before the call print("====") func() #code to execute after the call print("====") #we return the function wrap to assign it to our original function return wrap We decorate our function. @decorator def func(): print("Hello") func() #we call the function outputs: ==== Hello ==== We used the @ syntax to decorate the function, that similar to this: func = decorate(func) Hope this helped :)
16th Mar 2018, 2:54 AM
ƒred
ƒred - avatar
+ 5
Imagine you have three functions, that, say, print three different kinds of messages. Sometimes in your code you want to print them without calling attention, but sometimes you want to put some “====“ stuff before and after the message. You can do that in many ways, but using a single decorator is a good one. First, you won’t need to write extra message functions. Even if you added extra prints to before and after your function calls (instead of using a decorator), imagine that one day you want to change the line to “&&&&” instead. With a decorator you only need to rewrite a few lines of code, instead of multiple.
15th Mar 2018, 11:13 AM
Pedro Demingos
Pedro Demingos - avatar
+ 4
Here is an example of what a decorator may be useful for: https://code.sololearn.com/cD09ijlIS6Ev/?ref=app
25th Mar 2018, 4:30 PM
Denys Yeromenko
Denys Yeromenko - avatar
+ 2
My pleasure!
26th Mar 2018, 3:44 AM
Denys Yeromenko
Denys Yeromenko - avatar
+ 1
it's still not easy to understand concept, but thanks to you for your answer 😃
15th Mar 2018, 11:26 AM
Majid Ostovari
Majid Ostovari - avatar
+ 1
سلام مجید
24th Mar 2018, 5:19 PM
BuG DeV
BuG DeV - avatar
+ 1
اهل کجایین؟
25th Mar 2018, 9:43 PM
BuG DeV
BuG DeV - avatar
0
In your example, func() is going to work only with @decorator part, so it seems not to be expandable, but a bunch of unnecessary code :(( anyway that you for answering my question 😃
16th Mar 2018, 7:26 AM
Majid Ostovari
Majid Ostovari - avatar
0
thanks for your answer, I understand it with lots of practice 😊
25th Mar 2018, 5:20 PM
Majid Ostovari
Majid Ostovari - avatar