Created
November 23, 2015 11:33
-
-
Save arthuralvim/2a604fc27332b9f53a91 to your computer and use it in GitHub Desktop.
Estudando classes e properties.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # -*- coding: utf-8 -*- | |
| class MyClass(object): | |
| error_msgs = { | |
| 'integer': "This doesn't look like an integer." | |
| } | |
| def __init__(self, default=0, raise_errors=True): | |
| self.default = default | |
| self.raise_errors = raise_errors | |
| self.errors = [] | |
| self._value = None | |
| def clean_errors(self): | |
| self.errors = [] | |
| @property | |
| def value(self): | |
| return self._value or self.default | |
| @value.setter | |
| def value(self, value): | |
| try: | |
| int(value) | |
| except (TypeError, ValueError): | |
| if self.raise_errors: | |
| raise Exception(self.error_msgs.get('integer')) | |
| else: | |
| self.errors.append(self.error_msgs.get('integer')) | |
| return | |
| self._value = int(value) | |
| if __name__ == '__main__': | |
| klass = MyClass(raise_errors=False) | |
| print klass.value | |
| klass.value = 10 | |
| print klass.value | |
| klass.value = '200' | |
| print klass.value | |
| klass.value = '200-' | |
| klass.value = '200-' | |
| klass.value = '200-' | |
| print klass.errors | |
| klass.clean_errors() | |
| klass.value = '200-' | |
| print klass.value | |
| print klass.errors |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment