Created
December 20, 2018 13:22
-
-
Save Fhernd/7fe7d37c13f1f16f429009428cde4fc5 to your computer and use it in GitHub Desktop.
Agregación de atributos a una clase. Python.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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