Day_12 · 面向对象(二):继承与 __str__ #13
Reference in New Issue
Block a user
Delete Branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
今日知识点
class Dog(Animal):—— Dog 是 Animal 的"子类",自动拥有 Animal 的全部方法super():在子类方法里调用父类的方法(super().方法())__str__:定义"这个对象打印出来长什么样"(print(对象)时触发)先学(教程)
任务(后做)
新建
day12.py:__str__方法:super()——给 Animal 加一个info()方法打印我是动物,然后让 Dog 重写
info():先打印我是狗,再调用super().info(),调用
d.info()观察两行输出和顺序。完成标准
print(d)显示的是狗名提交方式:把
day12.py代码贴在当日工单评论里。参考解答(先做再看)
1
day12完成
1
。
`class Animal:
def init(self,name):
self.name=name
def str(self):
return self.name
def info(self):
print("我是动物")
def speak(self):
print("...")
class Dog(Animal):
def speak(self):
print(f"{self.name}:“汪汪”")
def info(self):
print("我是狗")
super().info()
class Cat(Animal):
def speak(self):
print(f"{self.name}:喵喵")
d=Dog("旺财")
c=Cat("咪咪")
d.speak()
c.speak()
print(d)
d.info()
`
12
1
。
Day_12 · 面向对象(二)继承与 str
Animal 基类 + Dog/Cat 重写 speak(),str 定制打印