Files
DailyChallenge_ProgrammingD…/Day_12/README.md
T

101 lines
2.9 KiB
Markdown
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.
# Day_12 · 面向对象(二):继承与 __str__
> 预计耗时:25~30 分钟
> Django 里所有模型都写 `class Article(models.Model)`——`models.Model` 就是被继承的"基类"。
> 今天亲手写一次继承,你就明白 Django 的模型为什么"自带保存能力"。
## 今日知识点
- **继承**:`class Dog(Animal):` —— Dog 是 Animal 的"子类",自动拥有 Animal 的全部方法
- **重写**:子类里再写一遍同名方法,就覆盖父类的实现
- **`super()`**:在子类方法里调用父类的方法(`super().方法()`)
- **`__str__`**:定义"这个对象打印出来长什么样"(`print(对象)` 时触发)
## 先学(教程)
- 菜鸟教程("面向对象"一节,重点看**继承**部分):https://www.runoob.com/python3/python3-class.html
- B站黑马教程(看讲"继承"的几集):https://www.bilibili.com/video/BV1qW4y1a7fU/
## 任务(后做)
新建 `day12.py`:
1. 基类 + 两个子类:
```python
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print("...")
class Dog(Animal):
def speak(self): # 重写:覆盖父类
print(f"{self.name}:汪汪!")
class Cat(Animal):
def speak(self):
print(f"{self.name}:喵喵!")
d = Dog("旺财")
c = Cat("咪咪")
d.speak() # 旺财:汪汪!
c.speak() # 咪咪:喵喵!
```
2. 给 Animal 加 `__str__` 方法:
```python
# 在 Animal 类里加:
def __str__(self):
return self.name
print(d) # 打印出来是 旺财 而不是 <__main__.Dog object at ...>
```
3. **进阶(加分)**:用 `super()`——给 Animal 加一个 `info()` 方法打印 `我是动物`,
然后让 Dog 重写 `info()`:先打印 `我是狗`,再调用 `super().info()`,
调用 `d.info()` 观察两行输出和顺序。
## 完成标准
- [ ] 汪汪 / 喵喵 输出正确
- [ ] `print(d)` 显示的是狗名
- [ ] 能说出"子类自动拥有父类的方法"这句话的意思
- [ ] (进阶)super() 两行输出顺序正确
**提交方式**:把 `day12.py` 代码贴在当日工单评论里。
## 参考解答(先做再看)
```python
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print("...")
def __str__(self): # 打印对象时显示的名字
return self.name
def info(self):
print("我是动物")
class Dog(Animal):
def speak(self):
print(f"{self.name}:汪汪!")
def info(self): # 进阶:super()
print("我是狗")
super().info() # 调用父类的 info
class Cat(Animal):
def speak(self):
print(f"{self.name}:喵喵!")
d = Dog("旺财")
c = Cat("咪咪")
d.speak()
c.speak()
print(d) # 旺财
d.info() # 我是狗 / 我是动物
```