Guest User

Untitled

a guest
Jan 24th, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.16 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3.  
  4. from __future__ import print_function
  5.  
  6. class ImmutabilityException(BaseException):
  7. pass
  8.  
  9. class ImmutableRecord(object):
  10.  
  11. def __init__(self, **kwargs):
  12. self._record = kwargs
  13. for name, value in kwargs.items():
  14. setattr(self, name, value)
  15. self._immutable = True
  16.  
  17. def __setattr__(self, name, value):
  18. if hasattr(self, '_immutable') and self._immutable:
  19. raise ImmutabilityException('Unable to modify {name} in immutable record object'.format(name=name))
  20. return super(ImmutableRecord, self).__setattr__(name, value)
  21.  
  22. def set(self, **kwargs):
  23. new_record = dict(self._record)
  24. new_record.update(kwargs)
  25. return self.__class__(**new_record)
  26.  
  27. class Person(ImmutableRecord):
  28.  
  29. def __init__(self, name, sex):
  30. super(Person, self).__init__(name=name, sex=sex)
  31.  
  32. def __str__(self):
  33. return '<Person name={name} sex={sex}>'.format(name=self.name, sex=self.sex)
  34.  
  35. jack = Person(name='Jack', sex='m')
  36. print(jack) # <Person name=Jack sex=m>
  37. jill = jack.set(name='Jill')
  38. print(jack) # <Person name=Jack sex=m>
  39. print(jill) # <Person name=Jill sex=m>
Add Comment
Please, Sign In to add comment