Answer the question
In order to leave comments, you need to log in
How do you understand decorators in Python?
I've been sitting for 3 days already .. for the life of me, I don't understand at all. I'm sitting writing code, it works, but I don't understand - how? where and what, why? Let's have an example like this:
def uppercase(func):
def wrapper():
original_result = func()
return f'Большие {original_result.upper()}'
return wrapper
@uppercase
def greet():
return 'маленькие буквы'
print(greet())
>>>Большие МАЛЕНЬКИЕ БУКВЫ
Answer the question
In order to leave comments, you need to log in
Then I had a question and a stupor - for some reason we do not return the result of the execution of the wrapper function, but return the function-object itself.
def f1(): return 1
a = f1() # присваиваем результат работы функции, т.е. в a будет 1
a = f1 # присваиваем саму функцию
# тогда a - это не результат работы функции f1, а сама функция f1
# и мы можем ее запустить
print(a() ) # выведет 1, т.к. мы через a запустили f1
@uppercase
def greet(): ...
# то когда мы запускаем функцию
greet()
# по факту запускается
uppercase(greet)()
original_result = func() # запускает переданную ему функцию на исполнение, в нашем случае greet
return f'Большие {original_result.upper()}' # и возвращает строку с результатами исполнения
And it itself is somehow called and executed, although we do not explicitly write it.
uppercase(greet)()
а т.к. uppercase(greet) возвращает wrapper
то uppercase(greet)() запускает wrapper()
do we just create a function uppercase(greet) that will always be called when we write greet()? And why then if uppercase(greet) returns an object of type function, how is it itself called?
@uppercase
def greet():
return 'маленькие буквы'
def greet():
return 'маленькие буквы'
greet = uppercase(greet)
You can read more about the technical implementation in this article https://habr.com/en/post/141411/
In short, the following happens - the decorator sets the link greet = wrapper
, so when greet() is called, wrapper() is called instead, and not defined in the original greet code.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question