Advertisement
Fhernd

descriptor.py

Dec 20th, 2018
1,481
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.92 KB | None | 0 0
  1. class Entero:
  2.     def __init__(self, nombre):
  3.         self.nombre = nombre
  4.  
  5.     def __get__(self, instancia, clase):
  6.         if instancia is None:
  7.             return self
  8.         else:
  9.             return instancia.__dict__[self.nombre]
  10.  
  11.     def __set__(self, instancia, valor):
  12.         if not isinstance(valor, int):
  13.             raise TypeError('Se requiere un argumento de tipo entero.')
  14.  
  15.         instancia.__dict__[self.nombre] = valor
  16.  
  17.     def __delete__(selfself, instancia):
  18.         del instancia.__dict__[self.nombre]
  19.  
  20. class Punto:
  21.     x = Entero('x')
  22.     y = Entero('y')
  23.  
  24.     def __init__(self, x, y):
  25.         self.x = x
  26.         self.y = y
  27.  
  28. if __name__ == '__main__':
  29.     punto = Punto(2, 5)
  30.  
  31.     print(punto.x, punto.y) # Invocación implicita de Punto.x.__get__(punto, Punto)
  32.  
  33.     punto.x = 3     # Invocación de Punto.x.__set__(punto, 3)
  34.     punto.y = 5.3   # Invocación de Punto.y.__set__(punto, 5.3)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement