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

47 lines
1.6 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_4 参考解答
=============
主题:面向对象(一)—— 类和实例。
建议:先自己写,写不出来再看;看完后关掉文件自己默写一遍。
"""
class User:
all_users = [] # 类属性:模拟数据库表
def __init__(self, name, email, age):
self.name = name
self.email = email
self.age = age
User.all_users.append(self) # 把新用户"存表"
def get_full_name(self):
return f"用户:{self.name}({self.email})"
def __str__(self):
# 给"人"看的:print(user) 时显示,Django admin 列表里显示的就是它
return self.name
def __repr__(self):
# 给"开发者调试"看的:要能还原出原对象,eval(repr(u)) 应得到相同信息
return f"User(name={self.name!r}, email={self.email!r}, age={self.age!r})"
if __name__ == '__main__':
u1 = User("zhangsan", "zs@163.com", 20)
u2 = User("lisi", "ls@163.com", 21)
u3 = User("wangwu", "ww@163.com", 19)
for u in User.all_users:
print(u, "->", repr(u))
# zhangsan -> User(name='zhangsan', email='zs@163.com', age=20)
# lisi -> User(name='lisi', email='ls@163.com', age=21)
# wangwu -> User(name='wangwu', email='ww@163.com', age=19)
restored = eval(repr(u1)) # __repr__ 的用途:可还原
print(restored.name, restored.email) # zhangsan zs@163.com
# 思考题答案:
# __str__ 面向普通用户/展示,__repr__ 面向开发者/调试,且要求无歧义可还原;
# 只实现 __repr__ 时,print() 会退而使用 __repr__;反之不会。