def
supper(f):
def inner():
#b=f()
return f().upper()
return inner
#@supper
def
display():
return "hello"
result=supper(display)
print(result())
print(display())
"""output:
HELLO
hello
"""
Whenever we would like to apply the
decorator function to the existing function, it is mandatory to send existing
function as a parameter to the decorator function.
Ex:
def
décor (fun):
…
def
normal():
…
result=décor(normal)
To apply the decorator function
automatically to any normal function, use @ symbol followed by decorator name
above the function definition.
@supper
def
display():
return "hello"
so no need to call the decorator
function explicitly sending normal function as a paratmeter.
Decorator chaining: A python
program to apply two decorators to the same function using @ symbol
#a decorator that increments the value
of a function by 2
def
decor1(fun):
def inner():
a=fun()
return a*2
return inner
#a decorator that doubles the value of a
function
def
decor2(fun):
def inner():
a=fun()
return a+2
return inner
#take a function to which decorator should
be applied
@decor1
@decor2
def
count():
return 4
""
@decor1
@decor2
this is equalant to
#result=decor1(decor2(count))
#print(result())
"""
"""output:
12
"""
Note:
décor, inner are user defined words, instead we can give any name convention.Related Video: https://youtu.be/Vm4BnLWTK4E
https://youtu.be/dqVMIgkZRiQ
Next:
Prev: Decorators