animal.py
class Animal: def __init__(self,name): self.name = name def eat(self): pass
dog.py
from animal import Animal class Dog(Animal): def __init__(self,name): super().__init__(name) def eat(self): print(self.name + '正在进食...')
cat.py
from animal import Animal class Cat(Animal): def __init__(self,name): super().__init__(name) def eat(self): print(self.name + "正在进食...")
person.py
class Person: #人喂狗 def feedDog(self,dog): dog.eat() #人喂猫 def feedCat(self,cat): cat.eat() def feedAnimal(self,animal): animal.eat()
测试
from person import Person from dog import Dog from cat import Cat ''' 测试模块 演示多态的使用: ''' #实例化人、狗、猫对象 p = Person() d = Dog('旺旺') c = Cat('咪咪') p.feedDog(d) p.feedCat(c) p.feedAnimal(d) p.feedAnimal(c)