Created
March 3, 2017 08:43
-
-
Save MOOOWOOO/c43f7c08c33aea358b19d572d6ac5cff to your computer and use it in GitHub Desktop.
SuperPower Model
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): | |
""" | |
Model 是所有 model 的基类 | |
@classmethod 是一个套路用法 | |
例如 | |
user = User() | |
user.db_path() 返回 User.txt | |
""" | |
@classmethod | |
def db_path(cls): | |
""" | |
cls 是类名, 谁调用的类名就是谁的 | |
classmethod 有一个参数是 class(这里我们用 cls 这个名字) | |
所以我们可以得到 class 的名字 | |
""" | |
classname = cls.__name__ | |
path = '{}.txt'.format(classname) | |
return path | |
@classmethod | |
def all(cls): | |
""" | |
all 方法(类里面的函数叫方法)使用 load 函数得到所有的 models | |
""" | |
path = cls.db_path() | |
models = load(path) | |
# 这里用了列表推导生成一个包含所有 实例 的 list | |
# m 是 dict, 用 cls(m) 可以初始化一个 cls 的实例 | |
# 不明白就 log 大法看看这些都是啥 | |
ms = [cls(m) for m in models] | |
return ms | |
def __repr__(self): | |
""" | |
__repr__ 是一个魔法方法 | |
简单来说, 它的作用是得到类的 字符串表达 形式 | |
比如 print(u) 实际上是 print(u.__repr__()) | |
""" | |
classname = self.__class__.__name__ | |
properties = ['{}: ({})'.format(k, v) for k, v in self.__dict__.items()] | |
s = '\n'.join(properties) | |
return '< {}\n{} >\n'.format(classname, s) | |
def save(self): | |
""" | |
用 all 方法读取文件中的所有 model 并生成一个 list | |
把 self 添加进去并且保存进文件 | |
""" | |
log('debug save') | |
models = self.all() | |
log('models', models) | |
models.append(self) | |
l = [m.__dict__ for m in models] | |
path = self.db_path() | |
save(l, path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment