Skip to content

Instantly share code, notes, and snippets.

@odarbelaeze
Created April 8, 2017 14:16
Show Gist options
  • Save odarbelaeze/d233f6a54f36bbd9b68e6233c24b1852 to your computer and use it in GitHub Desktop.
Save odarbelaeze/d233f6a54f36bbd9b68e6233c24b1852 to your computer and use it in GitHub Desktop.
Decoradores y context managers.
import functools
import contextlib
@contextlib.contextmanager
def database():
print("creo una conexion")
db = {}
yield db
print ("cierro la conexion")
def requires_db(fun):
@functools.wraps(fun)
def wrapper(*args, **kwargs):
with database() as db:
return fun(db, *args, **kwargs)
return wrapper
def memory(fun):
@functools.wraps(fun)
def wrapper(*args, **kwargs):
print("Mido la memoria inicial")
result = fun(*args, **kwargs)
print("Mido la memoria final")
return result
return wrapper
def timer(fun):
@functools.wraps(fun)
def wrapper(*args, **kwargs):
print("Empiezo el reloj")
result = fun(*args, **kwargs)
print("Termino el reloj")
return result
return wrapper
# @memory
# @timer
@requires_db
def hola_mundo(db, mundo):
"""Doc"""
print(f"-- Usando la base de datos {db}")
print(f"-- hola {mundo}")
hola_mundo('marte')
print(hola_mundo.__doc__)
# En java
class Base(object):
def funcion(self):
print("--- Hola mundo")
class Decorada(Base):
def funcion(self):
print("Ahora esta decorado")
super().funcion()
print("Bien decorado")
Decorada().funcion()
# En python de nuevo
class Circulo(object):
def __init__(self, radio):
self.radio = radio
@property
def diametro(self):
return self.radio * 2
@diametro.setter
def diametro(self, value):
self.radio = value / 2
@classmethod
def from_diametro(cls, diametro):
print(cls.__name__)
return cls(diametro / 2)
c = Circulo(5.0)
c.diametro = 4
print(c.diametro)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment