Introduction to Decorators in Python
Decorators allow you to modify or enhance functions without changing their actual code. They are a powerful feature in Python.
1) Functions as First-Class Citizens
In Python, functions are first-class objects. This means you can:
- Assign a function to a variable
- Pass a function as an argument to another function
- Return a function from another function
- Store functions in lists, dictionaries, etc.
def greet():
print("Hello!")
say_hello = greet # Assign function to a variable
say_hello() # Output: Hello!
def call_func(f):
f()
call_func(greet) # Output: Hello!
def outer():
def inner():
print("Inside inner function")
return inner
my_func = outer()
my_func() # Output: Inside inner function
All of these concepts are what make decorators possible!
2) What is a Decorator?
A decorator is a function that:
- Takes another function as an argument
- Wraps or modifies its behavior
- Returns a new function
Think of it as a “wrapper” around a function that adds extra functionality.
3) Simple Decorator Example
def decorator_func(func):
def wrapper():
print("Before the function runs")
func()
print("After the function runs")
return wrapper
def say_hello():
print("Hello!")
decorated = decorator_func(say_hello)
decorated()
# Output:
# Before the function runs
# Hello!
# After the function runs
Here, decorator_func takes say_hello and returns a modified version.
4) Using @ Syntax
def decorator_func(func):
def wrapper():
print("Before the function runs")
func()
print("After the function runs")
return wrapper
@decorator_func
def say_hello():
print("Hello!")
say_hello()
# Output:
# Before the function runs
# Hello!
# After the function runs
The @decorator_func is just shorthand for say_hello = decorator_func(say_hello).
No comments:
Post a Comment