Skip to content

Commit

Permalink
Merge pull request mouredev#4339 from LuisOlivaresJ/main
Browse files Browse the repository at this point in the history
  • Loading branch information
kontroldev authored Jun 16, 2024
2 parents b3f99a7 + 4f08710 commit 61ba465
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions Roadmap/24 - DECORADORES/python/LuisOlivaresJ.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
"""
* Explora el concepto de "decorador" y muestra cómo crearlo
* con un ejemplo genérico.
"""

#Decorator wraps a function, modifying its behavior.

#Example
import functools


def do_twice(func):
@functools.wraps(func) # Used to preserve information about the original function.
def wraper(*args, **kwargs):
func(*args, **kwargs)
return func(*args, **kwargs)

return wraper

@do_twice
def say_something(name):
print(f"Hello, {name}!")
return f"Goodbye {name}!"


msg = say_something("Luis") # Hello!\nHello!
print(msg)


"""
* Crea un decorador que sea capaz de contabilizar cuántas veces
* se ha llamado a una función y aplícalo a una función de tu elección.
"""

calls_to_my_function = 0

def decorator(func):
def wraper():
global calls_to_my_function

func()
calls_to_my_function += 1
print(f"Number of calls to my_function: {calls_to_my_function}")
return wraper
#return func

@decorator
def my_function():
print("Inside my function!")

my_function()
my_function()
my_function()

0 comments on commit 61ba465

Please sign in to comment.