+ 4
I doesn't understand the "decoraters " topic.can anyone explain please?
Explain with relevant examples.
2 odpowiedzi
+ 1
Do you mean the decorators?
In Python, all is object. Even a function is an object. That's why the following code is valid :
def func() :
pass
func = 1
A decorator is a function, or a class that modify the behavior of a function. E.g
word = False
def decorator(function):
def decorate():
print("Not good")
if word:
return function
return decorate
@decorator
def good():
print("good")
good()
#outputs Not good
Explanation :
You can create a function inside an other function and then return it. That's the case here : decorate function is declared in site decorator function, and is then returned (because word is False).
Function decorator takes as parameter an other function (good). Here, if word is True, then function good is returned and it changes nothing. Else, function decorate is returned, and the output is "Not good".
@decorator is equal to good = decorator(good)
#good become function decorate and prints "NOT good".
+ 1
decorators are function that modify/add to a function. consider this example: You are building a blog website with python. you can see any of the blog but to comment you have to log in. this is a very common example and perfect to explain decorators.
in the example above. when you are trying to display a post on the blog you just call the display function
def display():
...functions here...
pass
now look at the “add” function. the user need to be logged in before they add comment or a create a post so you add a decorator to the “add” function
@loggedin
def add():
...functions here...
pass
This decorator redirect the user to log in if they are not logged and if they are you just move to the “add” function.
in this case you are putting the “loggedin” in its own function so you can reause for example if you also have an “edit” function that allow a user to edit their posts or delete them. In this case you wrote the “loggedin” function once and used it for add/edit/delete functions