A decorator is a special type of function or class that allows you to modify the behavior of other functions or classes without directly changing their source code.
Decorators provide a way to wrap or modify the functionality of the decorated object, adding extra features or functionality.
Decorators are typically used to extend or enhance the behavior of functions or classes, such as adding logging, authentication, caching, input validation, or timing functionality.
They help in keeping the code modular, reusable, and maintainable by separating the core functionality from the additional concerns.
In Python, decorators are implemented using the @decorator_name
syntax, where decorator_name
is the name of the decorator function or class.
The decorator is applied by placing it directly above the definition of the function or class that you want to decorate.
Example for decorators in python
def uppercase_decorator(function):
def wrapper():
result = function()
uppercase_result = result.upper()
return uppercase_result
return wrapper
@uppercase_decorator
def greet():
return "hello, world!"
print(greet()) # Output: HELLO, WORLD!
Code language: Python (python)
In this example, we have a decorator called uppercase_decorator
.
It takes a function as an argument and returns a new function wrapper
that wraps around the original function.
The wrapper
function modifies the result of the original function by converting it to uppercase before returning it.
The @uppercase_decorator
syntax is a shorthand way of applying the decorator to the greet
function. It is equivalent to calling greet = uppercase_decorator(greet)
.
When we call greet()
, the decorator is applied automatically, and the output is transformed to uppercase, printing “HELLO, WORLD!” instead of “hello, world!”.
Decorators are a powerful feature in Python that allow you to modify the behavior of functions without changing their source code.
They are commonly used for adding additional functionality, such as logging, authentication, caching, or input validation, to functions without cluttering their implementation.
What are the commonly used decorators in Python?
There are several commonly used decorators in Python. Here are some examples:
1. @property
: This decorator allows you to define a method as a property, which can be accessed like an attribute, without explicitly calling it as a method. It is often used for creating getter and setter methods for class attributes.
class Circle:
def __init__(self, radius):
self.radius = radius
@property
def area(self):
return 3.14 * self.radius * self.radius
circle = Circle(5)
print(circle.area) # Output: 78.5
Code language: Python (python)
2. @staticmethod
: This decorator is used to define a static method within a class. Static methods do not have access to the instance or class attributes and can be called directly on the class itself.
class MathUtils:
@staticmethod
def add(x, y):
return x + y
print(MathUtils.add(2, 3)) # Output: 5
Code language: Python (python)
3. @classmethod
: This decorator is used to define a class method within a class. Class methods take the class itself as the first argument instead of the instance and can be used to create alternative constructors or perform operations that involve the class itself.
class Circle:
def __init__(self, radius):
self.radius = radius
@classmethod
def from_diameter(cls, diameter):
radius = diameter / 2
return cls(radius)
circle = Circle.from_diameter(10)
print(circle.radius) # Output: 5.0
Code language: Python (python)
4. @staticmethod
and @classmethod
can also be used together as decorators in a class to define static methods and class methods simultaneously.
5. @abstractmethod
: This decorator is used in abstract base classes (ABCs) to define abstract methods that must be implemented by the subclasses.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
rectangle = Rectangle(4, 5)
print(rectangle.area()) # Output: 20
Code language: Python (python)
These are just a few examples of commonly used decorators in Python. Decorators provide a flexible way to modify the behavior of functions and classes, enabling code reuse and adding additional functionality.
Read More;
- How to do Single Line for Loop in Python
- What is Len() in Python With Example
- What does V mean in Python?
- What is Async and Await in Python With Example
- For i in Range Python Example
- Python Joblib Parallel For Loop Example
- How to Derive in Python
- What is ‘Self’ in Python With Example
- What is Keyword Argument in Python with Example?
- What is Inheritance With Examples in Python
- What is Token in Python With Example
- How to Use def in Python With Example