|
| 1 | +# ╔═════════════════════════════════════╗ |
| 2 | +# ║ Autor: Kenys Alvarado ║ |
| 3 | +# ║ GitHub: https://github.com/Kenysdev ║ |
| 4 | +# ║ 2024 - Python ║ |
| 5 | +# ╚═════════════════════════════════════╝ |
| 6 | + |
| 7 | +# ----------------------------------- |
| 8 | +# * DECORADORES |
| 9 | +# ----------------------------------- |
| 10 | +# Mas info: https://geekflare.com/es/python-decorators/ |
| 11 | + |
| 12 | +""" |
| 13 | +* EJERCICIO #1: |
| 14 | +* Explora el concepto de "decorador" y muestra cómo crearlo |
| 15 | +* con un ejemplo genérico. |
| 16 | +""" |
| 17 | +print("EJERCICIO #1:") |
| 18 | + |
| 19 | +# ______________________ |
| 20 | +# Decorando una funcion: |
| 21 | + |
| 22 | +def my_decorator(func): |
| 23 | + # *args para manejar un número variable de argumentos posicionales. |
| 24 | + # **kwargs para argumentos de palabras clave. |
| 25 | + def wrapper(*args, **kwargs): |
| 26 | + print("\nAntes de que se llame a la función.") |
| 27 | + func(*args, **kwargs) |
| 28 | + print("Despues de llamarla") |
| 29 | + return wrapper |
| 30 | + |
| 31 | +@my_decorator |
| 32 | +def say_hello(first_name: str, last_name: str): |
| 33 | + print(f"Hola, {first_name} {last_name}!") |
| 34 | + |
| 35 | +say_hello("Zoe", "Roy") |
| 36 | + |
| 37 | +# NOTA: Sin el decorador, esto seria el equivalente: |
| 38 | +my_decorator(say_hello("Ben", "Yun")) |
| 39 | + |
| 40 | +# ______________________ |
| 41 | +# Decorando una clase: |
| 42 | + |
| 43 | +def class_decorator(cls): |
| 44 | + class Wrapper(cls): |
| 45 | + def greet(self): |
| 46 | + print("\nAntes de llamar al método") |
| 47 | + super().greet() |
| 48 | + print("Después de llamar al método") |
| 49 | + return Wrapper |
| 50 | + |
| 51 | +@class_decorator |
| 52 | +class MyClass: |
| 53 | + def greet(self): |
| 54 | + print("Hola!") |
| 55 | + |
| 56 | +obj = MyClass() |
| 57 | +obj.greet() |
| 58 | + |
| 59 | +""" |
| 60 | +* EJERCICIO #2: |
| 61 | +* Crea un decorador que sea capaz de contabilizar cuántas veces |
| 62 | +* se ha llamado a una función y aplícalo a una función de tu elección. |
| 63 | +""" |
| 64 | +print("\nEJERCICIO #2:") |
| 65 | + |
| 66 | +def count_calls(func): |
| 67 | + def wrapper(*args): |
| 68 | + wrapper.calls += 1 |
| 69 | + func(*args) |
| 70 | + print(f"Ha sido llamada {wrapper.calls} veces") |
| 71 | + |
| 72 | + wrapper.calls = 0 |
| 73 | + return wrapper |
| 74 | + |
| 75 | +@count_calls |
| 76 | +def function_a(func_name: str): |
| 77 | + print(f"\nLa función '{func_name}':") |
| 78 | + |
| 79 | +@count_calls |
| 80 | +def function_b(func_name: str, example: str): |
| 81 | + print(f"\nLa función{func_name} - {example}:") |
| 82 | + |
| 83 | +function_a("A") |
| 84 | +function_a("A") |
| 85 | +function_a("A") |
| 86 | + |
| 87 | +function_b("B", "args_ejm") |
| 88 | +function_b("B", "args_ejm") |
| 89 | + |
0 commit comments