使用继承和多态性编写Python程序

问题描述 投票:0回答:1

当然!让我们深入研究一个与面向对象编程和继承相关的详细Python问题:

问题:理解Python继承

考虑以下场景,您正在为动物园设计系统。动物园里有各种不同特点的动物。使用面向对象编程实现一个基本的 Python 程序,该程序对动物园中的动物层次结构进行建模。使用继承来表示不同类型动物之间的关系。

以下是要求:

  1. 定义一个名为

    Animal
    的基类,具有以下属性和方法:

    • 属性:
      name
      (动物名称)和
      species
      (动物种类)。
    • 方法:
      make_sound()
      ,打印动物发出的通用声音。
  2. 创建两个派生类,

    Mammal
    Bird
    ,它们继承自
    Animal
    类。每个派生类应该有额外的属性和方法:

    • Mammal
      班级:

      • 属性:
        fur_color
        (毛皮颜色)和
        num_legs
        (腿数)。
      • 方法:
        give_birth()
        ,打印一条关于分娩的消息。
    • Bird
      班级:

      • 属性:
        feather_color
        (羽毛颜色)和
        can_fly
        (指示鸟是否会飞的布尔值)。
      • 方法:
        fly()
        ,打印一条消息,指示鸟是否在飞。
  3. 创建每个类的特定实例来代表动物园中的不同动物(例如狮子、海豚、老鹰)。为属性设置适当的值。

  4. 通过为每个实例调用基类和派生类的方法来演示继承的使用。

  5. 最后,实现一个名为

    Zoo
    的类,其中包含动物列表。在
    Zoo
    类中提供一个名为
    make_all_sounds()
    的方法,该方法迭代动物列表并为每个动物调用
    make_sound()
    方法。

在我的解决方案中,我想强调继承、多态性的使用,并演示程序如何对动物园中不同类型的动物之间的关系进行建模。

inheritance polymorphism
1个回答
0
投票

愿这能为您的问题提供正确的答案:

class Animal:
    def __init__(self, name, species):
        self.name = name
        self.species = species

    def make_sound(self):
        print("{} the {} makes a sound.".format(self.name, self.species))


class Mammal(Animal):
    def __init__(self, name, species, fur_color, num_legs):
        super().__init__(name, species)
        self.fur_color = fur_color
        self.num_legs = num_legs

    def give_birth(self):
        print("{} the {} gives birth.".format(self.name, self.species))


class Bird(Animal):
    def __init__(self, name, species, feather_color, can_fly):
        super().__init__(name, species)
        self.feather_color = feather_color
        self.can_fly = can_fly

    def fly(self):
         if self.can_fly:
            print("{} the {} is flying.".format(self.name, self.species))
         else:
            print("{} the {} cannot fly.".format(self.name, self.species))


class Zoo:
    def __init__(self):
        self.animals = []

    def add_animal(self, animal):
        self.animals.append(animal)

    def make_all_sounds(self):
        for animal in self.animals:
            animal.make_sound()


# instances 
lion = Mammal("Simba", "Lion", "Golden", 4)
dolphin = Mammal("Dolly", "Dolphin", "Gray", 0)
eagle = Bird("Garud", "Eagle", "Brown", True)

# inheritance and polymorphism
lion.give_birth()
dolphin.make_sound()
eagle.fly()

#add animals
zoo = Zoo()
zoo.add_animal(lion)
zoo.add_animal(dolphin)
zoo.add_animal(eagle)

# make all sounds
zoo.make_all_sounds()

© www.soinside.com 2019 - 2024. All rights reserved.