1.定义宠物类( Pet ),子类猫类(Cat),测试实例 cat-[’咪咪”,31,打印显示:‘咪咪’ 3岁,I can eat, I can drink, Ican shout, I can climb tree. 1、宠物都有属性姓名 (name)和年龄(age)2、宠物都有吃(eat)(Ican eat’)、喝 (drink)( Ican drink )、叫 (shout) (I can shout’)的方法了、猫有爬树 (climbTree)的方法 (I can cl inb Tree')
时间: 2024-03-16 07:43:56 浏览: 259
下面是宠物类(Pet)和子类猫类(Cat)的定义及测试实例代码:
```python
# 宠物类定义
class Pet:
def __init__(self, name, age):
self.name = name
self.age = age
def eat(self):
print("I can eat")
def drink(self):
print("I can drink")
def shout(self):
print("I can shout")
# 猫类定义,继承自宠物类
class Cat(Pet):
def climbTree(self):
print("I can climb tree")
# 测试实例
cat = Cat("咪咪", 3)
print("{} {}岁,".format(cat.name, cat.age), end="")
cat.eat()
cat.drink()
cat.shout()
cat.climbTree()
```
输出结果为:
```
咪咪 3岁,I can eat
I can drink
I can shout
I can climb tree
```
阅读全文