0

Python decorators 67.2 Python core

Hello people. I have a question about this specific problem from Lesson 67.2 in the python core course I dont understand how "def display_text(text):" and "def uppercase_decorator(func):" are linked together. I mean we just called "print(display_text(text)) and this function returns the text? Really confusing to me. I had no problem to catch up with the logic of the examples earlier in that lesson until this one showed up. Would appreciate it if someone could explain it to me so i understand it:) text = input() def uppercase_decorator(func): def wrapper(text): return func(text).upper() #your code goes here return wrapper @uppercase_decorator def display_text(text): return(text) print(display_text(text))

16th Nov 2022, 11:26 AM
BinaryBaron
BinaryBaron - avatar
1 Resposta
0
You have a function: def uppercase_decorator(func): def wrapper(text): return text.upper() return wrapper — This function takes another function as an argument, so the argument is called "func". And in this function there is a built-in function "wrapper" with its own argument taking the value of a string type, calling it "text", this function converts the string to uppercase. To bind one function to another, use the symbol "@" with the name of the function of interest, after which the bound function is written: @uppercase_decorator def display_text(text): return(text) — This entry is similar to the fact that if we assign these functions to any variable, thus binding them to each other: uppercase = uppercase_decorator(display_text) in this example the conditional variable "uppercase" becomes a function with an argument to the function "display_text" and printed: print(uppercase(text)) As you can see, the first entry with the "@" decorator is just shorter.
16th Nov 2022, 1:01 PM
Solo
Solo - avatar