PYTHON DECORATORS IN 7 MINUTES | PYTHON FULL COURSE - 2026

Опубликовано: 28 Июнь 2026
на канале: Tech With Machines
22
1

#pythondecorators #decoratorsinpython #pythondecorator


Python Decorators
A decorator in Python is a function that allows you to modify the behavior of another function or class. They are used to add additional functionality to existing code without modifying the original code itself. Decorators are commonly used for logging, access control, caching, and other cross-cutting concerns in software development.

How Do Decorators Work?
A decorator is essentially a function that takes another function (or method) as input and returns a new function that adds some kind of functionality to the original one.

The syntax for a decorator is simple:

python
Copy code
@decorator_function
def some_function():
pass
Here, the @decorator_function is a shortcut for:

python
Copy code
def some_function():
pass

some_function = decorator_function(some_function)
Creating a Simple Decorator
Let’s start by creating a simple decorator that prints a message before and after calling the decorated function:

python
Copy code
def my_decorator(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper

@my_decorator
def greet():
print("Hello!")

greet()
Output:

r
Copy code
Before function call
Hello!
After function call
Here, my_decorator is a function that takes greet() as input, and it wraps greet() with additional functionality (the print statements before and after calling the original function).

Decorator with Arguments
If the function you are decorating takes arguments, you need to modify the wrapper function to accept them as well:

python
Copy code
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Before function call")
result = func(*args, **kwargs)
print("After function call")
return result
return wrapper

@my_decorator
def greet(name):
print(f"Hello, {name}!")

greet("Alice")
Output:

r
Copy code
Before function call
Hello, Alice!
After function call
Here, *args and **kwargs allow the decorator to pass any number of positional and keyword arguments to the decorated function.

Using Built-in Decorators
Python provides several built-in decorators, such as @staticmethod, @classmethod, and @property.

@staticmethod: Used to define a static method in a class that doesn't need access to the instance (self) or class (cls).
@classmethod: Used to define a class method that takes cls as its first argument.
@property: Used to create getter and setter methods for class attributes.
Example with @staticmethod:

python
Copy code
class MyClass:
@staticmethod
def greet():
print("Hello, world!")

MyClass.greet() # Output: Hello, world!
Chaining Multiple Decorators
You can apply multiple decorators to a single function. The decorators are applied from bottom to top (the decorator closest to the function is applied first).

Example:

python
Copy code
def decorator1(func):
def wrapper():
print("Decorator 1")
func()
return wrapper

def decorator2(func):
def wrapper():
print("Decorator 2")
func()
return wrapper

@decorator1
@decorator2
def greet():
print("Hello!")

greet()
Output:

Copy code
Decorator 1
Decorator 2
Hello!
Using functools.wraps
When you decorate a function, the decorated function may lose its original metadata, such as its name, docstring, and function signature. To preserve the metadata, you can use functools.wraps.

Example:

python
Copy code
from functools import wraps

def my_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
print("Before function call")
result = func(*args, **kwargs)
print("After function call")
return result
return wrapper

@my_decorator
def greet(name):
"""This function greets the person by name."""
print(f"Hello, {name}!")

print(greet.__name__) # Output: greet
print(greet.__doc__) # Output: This function greets the person by name.
By using @wraps, the decorated function retains its original name and docstring.

Summary of Decorators
Purpose: Decorators add extra functionality to functions or methods without modifying their code.
Syntax: You use @decorator_name before a function definition.
Arguments: Decorators can pass arguments to the function being decorated.
Common Uses: Logging, caching, access control, and validation.
Decorators provide a powerful and flexible way to modify functions and methods in Python. They are often used in frameworks like Flask and Django for handling things like authentication, logging, and middleware.