Skip to content

Instantly share code, notes, and snippets.

@Fhernd
Created December 20, 2018 13:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fhernd/7fe7d37c13f1f16f429009428cde4fc5 to your computer and use it in GitHub Desktop.
Save Fhernd/7fe7d37c13f1f16f429009428cde4fc5 to your computer and use it in GitHub Desktop.
Agregación de atributos a una clase. Python.
class Entero:
def __init__(self, nombre):
self.nombre = nombre
def __get__(self, instancia, clase):
if instancia is None:
return self
else:
return instancia.__dict__[self.nombre]
def __set__(self, instancia, valor):
if not isinstance(valor, int):
raise TypeError('Se requiere un argumento de tipo entero.')
instancia.__dict__[self.nombre] = valor
def __delete__(selfself, instancia):
del instancia.__dict__[self.nombre]
class Punto:
x = Entero('x')
y = Entero('y')
def __init__(self, x, y):
self.x = x
self.y = y
if __name__ == '__main__':
punto = Punto(2, 5)
print(punto.x, punto.y) # Invocación implicita de Punto.x.__get__(punto, Punto)
punto.x = 3 # Invocación de Punto.x.__set__(punto, 3)
punto.y = 5.3 # Invocación de Punto.y.__set__(punto, 5.3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment