0

Decorators in python

Hello, I would be thankful if you could advice me. Do decorators modifies nested functions? For instance, in the following example, has the function ad() been modified by the decorator basic? def basic(func): def modified(): x=int(input(':')) y=int(input(':')) func(x,y) return modified @basic def ad(x,y): print(x+y) ad() If not then why when we call ad function it returns the decorated output?

22nd Nov 2022, 9:50 AM
Ruslan Guliyev
Ruslan Guliyev - avatar
2 ответов
+ 2
In short, yes. But only because it extends the functionality of the ad() function by wrapping it AND assigns this wrapped function to the name 'ad'. Using the @basic is just a simpler way of doing this: ad = basic(ad) They're the same: The name 'ad' now references the modified function, not the original. If you want a decorated function but still want to reference the original function, you could do something like this: ad_decor = basic(ad) ad(5,7) # call original ad, prints 12 ad_decor() # call modified ad, asks for # input, then sums and prints
22nd Nov 2022, 3:53 PM
Mozzy
Mozzy - avatar
+ 1
Mozzy Thank you very much! You helped me a lot!
23rd Nov 2022, 11:00 AM
Ruslan Guliyev
Ruslan Guliyev - avatar