Introduction to Decorators in Python
Python : Decorators
What is Decorators in Python?
Decorators
are a powerful feature in Python that allows programmers to modify or extend the functionality of existing functions or classes without modifying their source code. In other words, decorators enable us to add additional functionality to a function or class by wrapping it with another function or class.
Syntax of Decorators in Python:
In Python, decorators are created using the @
symbol followed by the name of the decorator function.
@decorator_function
def function():
# function body
Here, decorator_function
is the name of the decorator function, and function
is the name of the function that we want to decorate.
Let's create a simple example to understand how decorators work in Python.
Suppose we have a function that calculates the sum of two numbers:
def add(a, b):
return a + b
Now, let's say we want to add some additional functionality to this function, such as printing a message before and after the function call.
We can use a decorator
to achieve this:
def decorator_function(func):
def wrapper_function(a, b):
print("Before function call")
result = func(a, b)
print("After function call")
return result
return wrapper_function
@decorator_function
def add(a, b):
return a + b
print(add(2, 3))
// To apply the decorator to our original function `add`, we use the `@decorator_function` syntax
// before the function definition. When we call the add function with arguments 2 and 3, the decorator
// function is automatically applied
# Output
# Before function call
# After function call
# 5
Decorators are a powerful and flexible feature in Python that allows us to modify or extend the functionality of existing functions or classes without modifying their source code.
Decorators are widely used in many Python frameworks and libraries to add new features and capabilities to the existing codebase.
Previous Article
Next Article
Python Tutorials
- Hello World
- Variables and Types
- Lists
- Tuple
- Basic Operators
- Strings
- Conditions
- Loops
- Functions
- Classes and Objects
- Dictionaries
- Map
- Filter
- Reduce
- Sets
- Decorators
- Generators
- Modules and Packages
- Numpy Arrays
- Pandas Basics
- List Comprehensions
- Lambda functions
- Multiple Function Arguments
- Partial functions
- Regular Expressions
- Exception Handling
- Serialization
- Code Introspection