Advertisement
FutureDreams

Descriptors in Python

Oct 31st, 2021
1,100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.69 KB | None | 0 0
  1.  
  2. class TypedField:
  3.  
  4.     def __init__(self, _type, _name):
  5.         self._type = _type
  6.         self._name = f'_{_name}'
  7.  
  8.     def __set__(self, instance, value):
  9.         if not isinstance(value, self._type):
  10.             raise TypeError("Only %s type is supported, you provided %s" % (self._type, type(value)))
  11.         setattr(instance, self._name, value)
  12.  
  13.     def __get__(self, instance, owner):
  14.         return getattr(instance, self._name)
  15.  
  16.  
  17. class PythonUZ:
  18.     member_count = TypedField(int, 'member_count')
  19.     title = TypedField(str, 'title')
  20.  
  21.  
  22. pyuz = PythonUZ()
  23. pyuz.member_count = 1914
  24. print(pyuz.member_count)
  25. pyuz.title = 42  # raises TypeError as we provided int instead of str
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement