0

Decorators Practice "Uppercasing"

I've been understanding most of the lessons in the Python Core course, but Decorators have broken my mind. Specifically, the "Uppercasing" Practice. I do not understand how to take the text that is being passed in as the argument and capitalze it inside the "Wrapper" function. Everything I try results in an error or a "None" result. Examples: text = input() def uppercase_decorator(func): def wrapper(text): #your code goes here text = text.upper() return wrapper @uppercase_decorator def display_text(text): return(text) print(display_text(text)) -------------------------------- text = input() def uppercase_decorator(func): def wrapper(text): #your code goes here func(text.upper()) return wrapper @uppercase_decorator def display_text(text): return(text) print(display_text(text)) -------------------------------- text = input() def uppercase_decorator(func): def wrapper(text): #your code goes here func(text) text = text.upper() return wrapper @uppercase_decorator def display_text(text): return(text) print(display_text(text))

6th Jul 2021, 4:14 PM
Michael
Michael - avatar
6 Respuestas
- 1
I was missing a "return" in the second example. It should have read: def uppercase_decorator(func): def wrapper(text): #your code goes here return func(text.upper()) return wrapper My problem was is that I was thinking in terms of functions like print() that aren't chaning the argument. But since the argument is changing, I need to a return to bring back the value that was changed.
6th Jul 2021, 6:28 PM
Michael
Michael - avatar
+ 1
def uppercase_decorator(func) def wrapper(*args,**kwargs): res = func(*args,**kwargs) return res.upper() return wrapper taking generic *args, **kwargs allow decorator to work with any function wich return a string... res store the result of decorated function call return res upper() to return the result string uppercased if you want to make the decorator able to work with quite any return value type, use: return str(res).upper()
6th Jul 2021, 4:39 PM
visph
visph - avatar
+ 1
My code, it works. text = input() def uppercase_decorator(func): def wrapper(text): #your code goes here print(text.upper()) return wrapper @uppercase_decorator def display_text(text): return(text) display_text(text)
27th Jul 2021, 1:09 PM
David Tom
David Tom - avatar
+ 1
This woked fpr me: #your code goes here return func(text.upper()) return wrapper
18th Nov 2021, 10:57 AM
Stefan Bartl
Stefan Bartl - avatar
0
you should provide your failing code(s) try, in order we can explain what you are making wrong ^^
6th Jul 2021, 4:19 PM
visph
visph - avatar
0
@visph I've updated the question with three examples of what I have tried.
6th Jul 2021, 4:30 PM
Michael
Michael - avatar