Fundamentos de Programaci贸n y Python
驴Por qu茅 aprender Python?
Introducci贸n a Python
Conceptos B谩sicos de Programaci贸n
Pr谩ctica: Te doy la bienvenida a los ejercicios interactivos
Manipulaci贸n de Cadenas de Texto en Python
Enteros, Flotantes y Booleanos
Todo lo que Debes Saber sobre print en Python
Operaciones Matem谩ticas en Python
Operaciones de Entrada/Salida en Consola
Colecci贸n y Procesamiento de Datos en Python
Listas
M茅todo slice
Listas de m谩s dimensiones y Tuplas
Aplicaci贸n de Matrices
Diccionarios
Comprehension Lists en Python (CLASE NUEVA)
Control de Flujo en Python
Estructuras condicionales
Bucles y Control de Iteraciones
Generadores e Iteradores
Funciones y Manejo de Excepciones en Python
Uso de Funciones en Python
Funciones Lambda y Programaci贸n Funcional en Python
驴C贸mo realizar una funci贸n recursiva en Python?
Manejo de Excepciones y Uso de Pass (CLASE NUEVA)
Programaci贸n Orientada a Objetos en Python
Fundamentos de Programaci贸n Orientada a Objetos en Python
Ejercicio Biblioteca con POO
Herencia en POO con Python
Objetos heredados
Los 4 pilares de la programacion orientada a objetos
Uso de super() en Python (CLASE NUEVA)
Superando los Fundamentos de Programaci贸n Orientada a Objetos en Python
Lectura y escritura de archivos
Manejo de Archivos .TXT (CLASE NUEVA)
Manejo de Archivos CSV (CLASE NUEVA)
Manejo de Archivos JSON (CLASE NUEVA)
Biblioteca est谩ndar de Python
Biblioteca est谩ndar en Python (CLASE NUEVA)
Librer铆a Os, Math y Random (CLASE NUEVA)
Librer铆a Statistics y An谩lisis Estad铆stico (CLASE NUEVA)
Proyecto final: Guerra naval
Conceptos avanzados de Python
Recapitulaci贸n de lo aprendido hasta ahora
Escribir c贸digo Pythonico y profesional
Comentarios y Docstrings en Python
Scope y closures: variables locales y globales
Anotaciones de tipo
Validaci贸n de tipos en m茅todos
Librer铆a Collections y Enumeraciones
Decoradores
Decoradores en Python
Decoradores anidados y con par谩metros
Uso de Decoradores en clases y m茅todos
M茅todos y estructura de clases en Python
M茅todos m谩gicos
Sobrecarga de operadores
Implementaci贸n de `if __name__ == "__main__":`
Metaprogramaci贸n en Python
Uso de *args y **kwargs
M茅todos privados y protegidos
Gesti贸n avanzada de propiedades
M茅todos est谩ticos y de clase avanzados
Programaci贸n concurrente y as铆ncrona
Introducci贸n a la concurrencia y paralelismo
Threading y multiprocessing en Python
Asincronismo con asyncio
Asincronismo y concurrencia
Creaci贸n de m贸dulos y paquetes
Creaci贸n de m贸dulos en Python
Gesti贸n de paquetes
Publicaci贸n de paquetes en PyPI
Proyecto final
Implementaci贸n de un sistema completo
Implementaci贸n de un Sistema Completo
You don't have access to this class
Keep learning! Join and start boosting your career
Decorators in Python are a powerful tool that allows you to modify or extend the behavior of functions or methods, without altering your original code. This approach is especially useful in a professional environment where you often want to add behaviors before or after the execution of a main function.
A decorator in Python starts by creating a function that acts on another function. This process involves:
For example, consider a basic decorator that prints messages before and after a function:
def my_function(parameter): print(f "Processing: {parameter}")
def my_decorator(func): def wrapper(*args, **kwargs): print("Before executing the function....") result = func(*args, **kwargs) print("After executing the function...") return result return wrapper
# Apply decorator@my_decoratordef process_payment(): print("Processing payment...")
process_payment()
To better understand decorators, we will consider an example where functionality is added before and after a function that processes a payment:
The basic function process_payment
is defined:
def process_payment(): print("Processing payment...")
A decorator is created that adds logs before and after executing the function:
def log_decorator(func): def wrapper(): print("Starting transaction log...") func() print("Transaction log completed.") return wrapper.
The decorator is applied using the @
symbol and the function is executed:
@log_decoratordef process_payment(): print("Processing payment...")
process_payment()
Decorators can also be useful to check permissions before executing functions. Suppose we want to control access to a function that deletes employees, only allowing the action to administrators:
We define a function that deletes an employee, based on a data dictionary:
def remove_employee(employee): print(f "Employee {employee['name']} has been removed.")
A decorator is created to verify the employee's role:
def verify_access(func): def wrapper(employee): if employee.get('role') == 'admin': return func(employee) else: print("Access denied: only administrators can access.") return wrapper.
The decorator is applied and tested with different roles:
@check_accessdef delete_employee(employee): print(f "Employee {employee['name']} has been deleted.")
admin = {'name': 'Carlos', 'role': 'admin'}employee = {'name': 'Ana', 'role': 'employee'}
delete_employee(admin)delete_employee(employee)
This practical example shows how you can control which actions are allowed for whom, which is essential in collaborative and security environments.
As an additional challenge, try implementing a decorator that records all actions performed by an employee in a text file. This will not only help you consolidate the use of decorators, but will also encourage the reuse and extension of functionality in your code.
You will continue to learn about decorators and their advanced uses, such as including parameters and nesting multiple decorators. Continue on your programming learning journey!
Contributions 47
Questions 2
Want to see more contributions, questions and answers from the community?