定义Dog、Cat 和 Elephant 类:
描述 猫,狗,大象的饮食行为
class Dog:
def eat_dog_food(self):
print("Feeding the dog with dog food")
class Cat:
def eat_cat_food(self):
print("Feeding the cat with cat food")
class Elephant:
def eat_grass(self):
print("Feeding the elephant with grass")
定义Feeder 类:
Feeder
类定义了一个feed()
方法,它接受一个动物对象作为参数。- 在
feed()
方法中,它使用isinstance()
函数检查传入的动物对象是Dog
、Cat
还是Elephant
。 - 根据动物的类型,它调用相应的方法来"喂养"该动物。例如,如果传入的是
Dog
对象,它会调用eat_dog_food()
方法。
class Feeder:
def feed(self, animal):
if isinstance(animal, Dog):
animal.eat_dog_food()
elif isinstance(animal, Cat):
animal.eat_cat_food()
elif isinstance(animal, Elephant):
animal.eat_grass()
dog = Dog()
cat = Cat()
elephant = Elephant()
feeder = Feeder()
feeder.feed(dog)
feeder.feed(cat)
feeder.feed(elephant)
输出结果:
完整代码:
class Dog:
def eat_dog_food(self):
print("Feeding the dog with dog food")
class Cat:
def eat_cat_food(self):
print("Feeding the cat with cat food")
class Elephant:
def eat_grass(self):
print("Feeding the elephant with grass")
class Feeder:
def feed(self, animal):
if isinstance(animal, Dog):
animal.eat_dog_food()
elif isinstance(animal, Cat):
animal.eat_cat_food()
elif isinstance(animal, Elephant):
animal.eat_grass()
dog = Dog()
cat = Cat()
elephant = Elephant()
feeder = Feeder()
feeder.feed(dog)
feeder.feed(cat)
feeder.feed(elephant)