Last active
March 28, 2018 07:15
-
-
Save bao-qian/c1c60e667e2599aa00262b2bc00867b6 to your computer and use it in GitHub Desktop.
python orm
This file contains 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
class Model(object): | |
id: int = None | |
def __init__(self, **kwargs): | |
annotations = {**self.__annotations__, **Model.__annotations__} | |
for name, annotated in annotations.items(): | |
if name in kwargs: | |
value = kwargs.get(name) | |
value = annotated(value) | |
setattr(self, name, value) | |
class User(Model): | |
username: str | |
if __name__ == '__main__': | |
print(User.__dict__, User.__annotations__) | |
f1 = User(username='username1') | |
print(f1.__dict__, f1.__annotations__, id(f1.username)) | |
f2 = User(username='username2') | |
print(f2.__dict__, id(f2.username)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
在 init 阶段可以拿到所有的字段定义和类型和默认值。想怎么改都行了。