Files
DailyChallenge_ProgrammingD…/Day_5/参考解答.py
T

68 lines
1.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""
Day_5 参考解答
=============
主题:面向对象(二)—— 继承。
建议:先自己写,写不出来再看;看完后关掉文件自己默写一遍。
"""
import time
class BaseModel:
objects = [] # 类属性:模拟数据库表(所有子类共用)
def save(self):
BaseModel.objects.append(self)
print(f"[DB] 已保存 {type(self).__name__}: {self}")
def delete(self):
BaseModel.objects.remove(self)
print(f"[DB] 已删除 {self}")
def to_dict(self):
return dict(self.__dict__) # 实例的所有属性 => 字典
def __str__(self):
return f"<{type(self).__name__}#{id(self)}>"
class Article(BaseModel):
def __init__(self, title, content, author):
self.title = title
self.content = content
self.author = author
self.created_at = time.strftime("%Y-%m-%d %H:%M:%S")
# 进阶:重写 save,先打日志,再调用父类逻辑
def save(self):
print(f"[LOG] 正在保存文章《{self.title}》...")
super().save() # 父类的 save 负责真正"入库"
def __str__(self):
return f"<Article: {self.title}>"
class Comment(BaseModel):
def __init__(self, content, author):
self.content = content
self.author = author
def __str__(self):
return f"<Comment: {self.content[:10]}...>"
if __name__ == '__main__':
a1 = Article("Django 入门", "从 Hello World 开始", "zhangsan")
a1.save() # 触发重写后的 save(带日志 + super)
c1 = Comment("写得太好了!", "lisi")
c1.save()
for obj in BaseModel.objects:
print(obj.to_dict())
print(issubclass(Article, BaseModel)) # True
print(isinstance(a1, BaseModel)) # True
a1.delete()
print(len(BaseModel.objects)) # 1(只剩评论)