Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class TypedProperty:
- _VALUE_PREFIX = '_tpvalue_'
- def __init__(self, _type):
- self._type = _type
- def __get__(self, instance, cls):
- if instance is None:
- return cls.__dict__[self.name]
- if self.name not in instance.__dict__:
- return cls.__dict__[TypedProperty._VALUE_PREFIX+self.name]
- return instance.__dict__[self.name]
- def __set__(self, instance, value):
- print('set')
- if not isinstance(value, self._type):
- raise ValueError(f'attribute {self.name!r} must be {self._type.__name__}, but got {value.__class__.__name__} instead.')
- if instance is None:
- print('hey')
- if self.name in instance.__dict__:
- instance.__dict__[self.name] = value
- else:
- setattr(instance.__class__, TypedProperty._VALUE_PREFIX+self.name, value)
- def __delete__(self, instance):
- self.__set__(instance, self._type())
- def __set_name__(self, cls, name):
- print('set name')
- self.name = name
- setattr(cls, TypedProperty._VALUE_PREFIX+name, self._type())
- © 2019
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement