以下是一种可能的重构和优化方式:

import random

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

    def make_sound(self):
        print(f"{self.name} the {self.species} says {self.sound}!")

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

    def add_animal(self, animal):
        if isinstance(animal, Animal):
            self.animals.append(animal)
            print(f"{animal.name} the {animal.species} has been added to the zoo!")
        else:
            print("Invalid animal type. Only instances of Animal class can be added to the zoo.")

    def list_animals(self):
        if len(self.animals) == 0:
            print("The zoo is empty.")
        else:
            print("The zoo has the following animals:")
            for animal in self.animals:
                print(f"- {animal.name} the {animal.species}")

    def random_animal_sound(self):
        if len(self.animals) == 0:
            print("There are no animals in the zoo.")
        else:
            animal = random.choice(self.animals)
            animal.make_sound()

# Example usage:

zoo = Zoo()

lion = Animal("Simba", "lion", "roar")
zoo.add_animal(lion)

tiger = Animal("Shere Khan", "tiger", "growl")
zoo.add_animal(tiger)

elephant = Animal("Dumbo", "elephant", "trumpet")
zoo.add_animal(elephant)

zoo.list_animals()

zoo.random_animal_sound()

主要的变化包括:

  • 将 Animal 类和 Zoo 类分别定义在不同的代码块中,使得代码结构更清晰。
  • 在 Animal 类中添加了一个 make_sound 方法来打印动物的叫声,使得其与 Zoo 类更加解耦合。
  • 修改了 add_animal 方法中的判断逻辑,使得只有 Animal 类的实例才能被添加到动物园中。
  • 在 list_animals 方法中添加了对动物园是否为空的判断。
  • 在 random_animal_sound 方法中添加了对动物园是否为空的判断,并且使用 random.choice 方法来随机选择一个动物并打印其叫声。
  • 在示例代码中演示了如何创建动物和添加到动物园中,以及如何列出动物园中的所有动物和随机播放一个动物的叫声。
把这段代码重构一下,整理并优化

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

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