Last active
September 9, 2019 09:48
-
-
Save stoensin/e90860aa6df3666cc83da50c48ab0577 to your computer and use it in GitHub Desktop.
使用特性工厂方法避免设置过多特性 影响代码可读性
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
| def typed_property(name, expected_type): | |
| storage_name = '_' + name | |
| @property | |
| def prop(self): | |
| return getattr(self, storage_name) | |
| @prop.setter | |
| def prop(self, value): | |
| if not isinstance(value, expected_type): | |
| raise TypeError('{} must be a {}'.format(name, expected_type)) | |
| setattr(self, storage_name, value) | |
| return prop | |
| #use | |
| class Person: | |
| name = typed_property('name', str) | |
| age = typed_property('age', int) | |
| def __init__(self, name, age): | |
| self.name = name | |
| self.age = age | |
| from functools import partial | |
| String = partial(typed_property, expected_type=str) | |
| Integer = partial(typed_property, expected_type=int) | |
| class Person: | |
| name = String('name') | |
| age = Integer('age') | |
| def __init__(self, name, age): | |
| self.name = name | |
| self.age = age |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment