Advertisement
Guest User

TypedProperty

a guest
Nov 20th, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.18 KB | None | 0 0
  1. class TypedProperty:
  2.  
  3.     _VALUE_PREFIX = '_tpvalue_'
  4.  
  5.     def __init__(self, _type):
  6.         self._type = _type
  7.  
  8.    
  9.     def __get__(self, instance, cls):
  10.         if instance is None:
  11.             return cls.__dict__[self.name]
  12.         if self.name not in instance.__dict__:
  13.             return cls.__dict__[TypedProperty._VALUE_PREFIX+self.name]
  14.         return instance.__dict__[self.name]
  15.        
  16.        
  17.  
  18.  
  19.     def __set__(self, instance, value):
  20.         print('set')
  21.         if not isinstance(value, self._type):
  22.             raise ValueError(f'attribute {self.name!r} must be {self._type.__name__}, but got {value.__class__.__name__} instead.')
  23.         if instance is None:
  24.             print('hey')              
  25.         if self.name in instance.__dict__:
  26.             instance.__dict__[self.name] = value
  27.         else:
  28.             setattr(instance.__class__, TypedProperty._VALUE_PREFIX+self.name, value)
  29.  
  30.  
  31.        
  32.     def __delete__(self, instance):
  33.         self.__set__(instance, self._type())
  34.  
  35.  
  36.     def __set_name__(self, cls, name):
  37.         print('set name')
  38.         self.name = name
  39.         setattr(cls, TypedProperty._VALUE_PREFIX+name, self._type())
  40. © 2019
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement