Explain decorators in python
Decorator :
- Decorator is the name used for a software design pattern.
- It is used to alter functions and methods.
- Decorators work as wrappers, modifying the behavior of the code before and after a target function execution, without the need to modify the function itself, augmenting the original functionality.
- Basically, a decorator takes in a function, adds some functionality and returns it.
- Multiple decorators can be chained in Python.
- For ex :
def addOne(myFun):
def addOneInside(*args,**kwrgs):
return myFun(*args,**kwrgs) + 1
return addOneInside
@addOne
def oldFun( x = 1 ):
return x
print oldFun(564) # prints 565
Comments
Post a Comment