写继承实例,要求有重写方法和新方法
时间: 2024-01-18 07:01:57 浏览: 24
下面是一个继承实例,其中子类重写了父类的方法并添加了新的方法:
```python
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def speak(self):
print(f"{self.name} is speaking.")
class Cat(Animal):
def __init__(self, name, age, color):
super().__init__(name, age)
self.color = color
def speak(self):
print(f"{self.name} is meowing.")
def scratch(self):
print(f"{self.name} is scratching.")
```
在上面的代码中,`Animal` 类有一个 `speak` 方法,用于输出动物正在发出声音。`Cat` 类继承了 `Animal` 类,并重写了 `speak` 方法,用于输出猫正在喵喵叫。`Cat` 类还添加了一个新的方法 `scratch`,用于输出猫正在抓东西。
现在我们可以创建一个 `Cat` 对象,并调用它的方法:
```python
cat = Cat("Tom", 3, "white")
cat.speak() # 输出:Tom is meowing.
cat.scratch() # 输出:Tom is scratching.
```