+ 2
How can i know where to use decorators? And why to use them?
it seems without decorators the code can run correctly :|
9 Réponses
+ 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 :)
+ 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.
+ 4
Here is an example of what a decorator may be useful for:
https://code.sololearn.com/cD09ijlIS6Ev/?ref=app
+ 2
My pleasure!
+ 1
it's still not easy to understand concept, but thanks to you for your answer 😃
+ 1
سلام مجید
+ 1
اهل کجایین؟
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 😃
0
thanks for your answer, I understand it with lots of practice 😊