类中反射的应用

#利用反射,构造对象
#反射取值可以不全取fileds中的键,只取部分
class UpDownModel(object):
fields = {
"id": "ID",
"choice": "赞或踩", # 1,表示是赞;0,表示是踩
}

def __init__(self, row_dict):
for k in self.fields:
setattr(self, k, row_dict.get(k)) #.get取值
# self.id = row_dict.get("id")
# self.choice = row_dict.get("choice")

#调用UpDownModel对象
def fetch_up_down(user_id, aid):
with Connect() as conn:
sql = "select id,choice from up_down where user_id=%s and article_id=%s"
result = conn.fetch_one(sql, user_id, aid)
if result:
return UpDownModel(result)
#反射取值可以不全取fileds中的键,只取部分
class ArticleModel(object):
fields = {
"title": "标题",
"text": "内容",
"read_count": "阅读数",
"comment_count": "评论数",
"up_count": "赞数",
"down_count": "踩数",
"nickname": "作者",
}

# {"title":xxxx,"text":xxxx,read_count:"xxx"}
def __init__(self, row_dict):
for key in self.fields:
setattr(self, key, row_dict.get(key))
# self.title = row_dict.get("title")
# self.text = row_dict.get("title")

@classmethod
def db_fields(cls):
return ",".join([k for k in cls.fields])

def show(self):
row_display = ["title", 'text']
for k in row_display:
line = "{}:{}".format(self.fields[k], getattr(self, k)) #getattr 取值
print(line)

column_display = ["nickname", "read_count", "comment_count", "up_count", "down_count"]
section_list = []
for k in column_display:
section_list.append("{}:{}".format(self.fields[k], getattr(self, k)))
others = " ".join(section_list)
print(others)

#调用ArticleModel对象
def get_article(article_id):
with Connect() as conn:
sql = """
select
{}
from
article
left join user on article.user_id = user.id
where article.id=%s""".format(ArticleModel.db_fields()) #调用ArticleModel对象
result = conn.fetch_one(sql, article_id)
if not result:
return None
if __name__ == '__main__':
ArticleModel({"title":'xxxx',"text":'xxxx','read_count':"1"}).show()
#未输入的默认为None
# 标题: xxxx
# 内容: xxxx
# 作者: None 阅读数: 1 评论数: None 赞数: None 踩数: None

上一篇:Dictionary字典映射


下一篇:formidable实现文件上传