+ 2
Decorators in python.
I made the decorators course in solo learn but I don't have pro, so I couldn't try it. I understand nothing! Can someone explain me decorators, higher order functions and this functions in functions AND give me examples why and how to use? This course I so short and badly to understand!!!
3 Risposte
+ 4
you don't need a pro account to write decorator functions.
there are external sources that can help you learn about decorators.
https://realpython.com/primer-on-JUMP_LINK__&&__python__&&__JUMP_LINK-decorators/
yes, i agree, the courses have become less and less informative with each revision.
not enough explanation and examples, all for the sake of keeping the lesson format consistent and 'cute'. a case of form over function.
anyway, decorators are higher-order functions.
they accept functions as arguments. they call the function internally and perform additional operations on the result.
the @decorator is just a convenient syntax sugar.
the lesson have this example:
def uppercase(func):
def wrapper():
orig_message = func()
modified_message = orig_message.upper()
return modified_message
return wrapper
@uppercase
def greet():
return "Welcome!"
# Using the decorated function
print(greet())
if you comment out @uppercase, you could use uppercase like:
print(uppercase(greet)())
+ 3
Thank you! This article is so much better than the sololearn course!
+ 1
why this ⬇️?
uppercase(greet)()
because uppercase returns another function -> wrapper. you have to call that to get the final result. uppercase(greet)() is the same as wrapper().
it's awkward, thus the @uppercase decorator syntax. then you just have to use greet().