在Python中,多态可以通过继承和方法重写来实现。下面是一个简单的例子:

class Animal:
    def sound(self):
        pass

class Dog(Animal):
    def sound(self):
        print("Woof!")

class Cat(Animal):
    def sound(self):
        print("Meow!")

class Cow(Animal):
    def sound(self):
        print("Moo!")

animals = [Dog(), Cat(), Cow()]

for animal in animals:
    animal.sound()

在上面的例子中,Animal 是一个父类,DogCatCow 是子类。每个子类都重写了父类的 sound 方法,以实现各自的声音输出。在循环中,我们可以看到不同类型的动物对象调用了相同的方法 sound,但实际输出的声音不同。这就是多态的体现。

输出结果为:

Woof!
Meow!
Moo!
python 类中多态举例

原文地址: http://www.cveoy.top/t/topic/iZRR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录