- Trending Categories
- Data Structure
- Operating System
- MS Excel
- C Programming
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What are decorators in Python?
A Decorator is one of the most powerful design patterns in Python. Decorator is used to add new features to an already created object without modifying its structure. With Decorators, you can easily wrap another function for extending the wrapped function behaviour and this is done without modifying it permanently.
Functions are first-class objects
In Python, the functions are considered as first-class objects i.e. we can store the functions in a variable, return function from a function, etc.
Below are some examples displaying functions in Python useful for understanding Decorators.
Functions as objects
The functions are considered as object in this example. Here, the function demo() is assigned to a variable −
# Creating a function def demo(mystr): return mystr.swapcase() # swapping the case print(demo('Thisisit!')) sample = demo print(sample('Hello'))
Pass the function as an argument
In this the function is passed as an argument. The demo3() function calls demo() and demo2() function as a parameter.
def demo(text): return text.swapcase() def demo2(text): return text.capitalize() def demo3(func): res = func("This is it!") # Function passed as an argument print (res) # Calling demo3(demo) demo3(demo2)
tHIS IS IT! This is it!
Now, let us work around Decorators
Decorators in Python
In Decorators, the functions are taken as an argument into another function and then called inside the wrapper function. Let us see a quick example:
@mydecorator def hello_decorator(): print("This is sample text.")
The above can also be written as −
def demo_decorator(): print("This is sample text.") hello_decorator = mydecorator (demo_decorator)
def demoFunc(x,y): print("Sum = ",x+y) # outer function def outerFunc(sample): def innerFunc(x,y): # inner function return sample(x,y) return innerFunc # calling demoFunc2 = outerFunc(demoFunc) demoFunc2(10, 20)
Sum = 30
Applying Syntactic Decorator
The above example can be simplified using decorator with the @symbol. This eases applying decorators by placing @ symbol before the function we want to decorate −
# outer function def outerFunc(sample): def innerFunc(x,y): # inner function return sample(x,y) return innerFunc @outerFunc def demoFunc(x,y): print("Sum = ",x+y) demoFunc(10,20)
Sum = 30
Kickstart Your Career
Get certified by completing the courseGet Started