分别用抽象方法和和接口回调两种形式来实现多态,来写狗和猫的叫声
时间: 2024-02-09 11:12:32 浏览: 29
使用抽象方法实现多态:
```python
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def make_sound(self):
pass
class Dog(Animal):
def make_sound(self):
print("汪汪汪")
class Cat(Animal):
def make_sound(self):
print("喵喵喵")
def animal_sound(animal):
animal.make_sound()
dog = Dog()
cat = Cat()
animal_sound(dog) # 输出:汪汪汪
animal_sound(cat) # 输出:喵喵喵
```
使用接口回调实现多态:
```python
class Animal:
def make_sound(self):
pass
class Dog(Animal):
def make_sound(self):
print("汪汪汪")
class Cat(Animal):
def make_sound(self):
print("喵喵喵")
def animal_sound(animal):
animal.make_sound()
class AnimalSound:
def __init__(self, animal):
self.animal = animal
def make_sound(self):
animal_sound(self.animal)
dog = Dog()
cat = Cat()
animal_sound(dog) # 输出:汪汪汪
animal_sound(cat) # 输出:喵喵喵
animal_sound_obj = AnimalSound(dog)
animal_sound_obj.make_sound() # 输出:汪汪汪
animal_sound_obj.animal = cat
animal_sound_obj.make_sound() # 输出:喵喵喵
```
这两种方式都可以实现多态,不同之处在于抽象方法方式需要继承抽象类,并且必须实现抽象方法,而接口回调则是通过传递对象来实现。