python写一实现多态程序
时间: 2023-08-17 18:28:55 浏览: 57
好的,这里给出一个简单的 Python 多态示例代码:
```python
class Animal:
def __init__(self, name):
self.name = name
def sound(self):
pass
class Cat(Animal):
def sound(self):
print(self.name + " says meow")
class Dog(Animal):
def sound(self):
print(self.name + " says woof")
def animal_sound(animal):
animal.sound()
cat = Cat("Kitty")
dog = Dog("Buddy")
animal_sound(cat) # 输出 "Kitty says meow"
animal_sound(dog) # 输出 "Buddy says woof"
```
在这个例子中,我们定义了一个父类 `Animal` 和两个子类 `Cat` 和 `Dog`。每个子类都重写了父类的 `sound` 方法,以便根据其自身的属性输出不同的声音。然后我们定义了一个函数 `animal_sound`,该函数接受一个 `Animal` 类型的参数,并调用该对象的 `sound` 方法。由于 `Cat` 和 `Dog` 类都是 `Animal` 类型的子类,所以我们可以将 `cat` 和 `dog` 对象传递给 `animal_sound` 函数,并且该函数会正确地调用它们各自的 `sound` 方法,输出不同的声音。这就是多态的应用,同一个函数可以接受不同的对象并产生不同的行为。