|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | + |
| 4 | +class TypedProperty(object): |
| 5 | + |
| 6 | + def __init__(self, name, type, default=None): |
| 7 | + self._name = '-' + name |
| 8 | + self._type = type |
| 9 | + self._default = default if default else type() |
| 10 | + |
| 11 | + def __get__(self, instance, cls): |
| 12 | + return getattr(instance, self._name, self._default) |
| 13 | + |
| 14 | + def __set__(self, instance, value): |
| 15 | + if not isinstance(value, self._type): |
| 16 | + raise TypeError('value {0} is not of {1}'.format(value, |
| 17 | + self._type)) |
| 18 | + setattr(instance, self._name, value) |
| 19 | + |
| 20 | + def __delete__(self, instance, cls): |
| 21 | + raise AttributeError('can not delete attribute') |
| 22 | + |
| 23 | + |
| 24 | +class Book(object): |
| 25 | + |
| 26 | + title = TypedProperty('title', str) |
| 27 | + author = TypedProperty('author', str) |
| 28 | + year = TypedProperty('year', int) |
| 29 | + |
| 30 | + def __init__(self, title=None, author=None, year=None): |
| 31 | + if title: |
| 32 | + self.title = title |
| 33 | + if author: |
| 34 | + self.author = author |
| 35 | + if year: |
| 36 | + self.year = year |
| 37 | + |
| 38 | + def __str__(self): |
| 39 | + return '{0}\n {1}, {2}'.format(self.title, self.author, self.year) |
| 40 | + |
| 41 | + |
| 42 | +if __name__ == '__main__': |
| 43 | + import sys |
| 44 | + |
| 45 | + book1 = Book() |
| 46 | + print('showing defaults:') |
| 47 | + print(str(book1) + '\n') |
| 48 | + book1.title = 'Animal farm' |
| 49 | + book1.author = 'George Orwell' |
| 50 | + book1.year = 1945 |
| 51 | + print(str(book1) + '\n') |
| 52 | + book2 = Book('Alice in Wonderland', 'Lewis Carroll', 1865) |
| 53 | + print(str(book2) + '\n') |
| 54 | + try: |
| 55 | + book3 = Book(1984, 'George Orwell', 1948) |
| 56 | + except TypeError as error: |
| 57 | + sys.stderr.write('### error: {0}\n'.format(error)) |
| 58 | + sys.exit(1) |
| 59 | + sys.exit(0) |
0 commit comments