剧情:
假设你正在为一个动物园开发一个简单的管理系统。你需要创建一个程序,它能够跟踪不同动物的信息,包括它们的名字、年龄和种类。此外,你还需要能够添加新的动物到动物园中,以及显示所有动物的信息。
创建一个名为 Animal 的基类,包含属性 name(名字)、age(年龄)和 species(种类)。
在 Animal 类中,创建一个初始化方法 __init__ 来初始化这些属性。
创建一个名为 Zoo 的类,它包含一个动物列表作为其属性。
在 Zoo 类中,创建一个方法 add_animal 来添加新的动物到列表中。
创建另一个方法 display_animals 来打印出所有动物的信息。
为 Animal 类添加一个 __str__ 方法,以便在打印动物对象时返回一个格式化的字符串,包含动物的名字、年龄和种类。
测试你的程序,创建3个 Animal 对象,并将它们添加到 Zoo 对象中,然后显示所有动物的信息。
参考答案:
class Animal:
def __init__(self, name, age, species):
self.name = name
self.age = age
self.species = species
def __str__(self):
return f"Name: {self.name}, Age: {self.age}, Species: {self.species}"
class Zoo:
def __init__(self):
self.animals = []
def add_animal(self, animal):
self.animals.append(animal)
def display_animals(self):
for animal in self.animals:
print(animal)
# 测试代码
zoo = Zoo()
zoo.add_animal(Animal("Leo", 5, "Lion"))
zoo.add_animal(Animal("Molly", 3, "Elephant"))
zoo.add_animal(Animal("Nina", 2, "Giraffe"))
zoo.display_animals()
Ykfi2deHbBJ
This article connected with me on a personal level, thanks.
I never thought of that before; your perspective is stimulating.
ahQh5vVWPOe
The article is thoughtful and provides practical advice for readers. Thanks for sharing your insights with us.
I sincerely value the way your writing resonates your authentic character, creating a delightful conversation.
I like the way your blog provides a distinctive viewpoint on related topics. It’s truly inspiring.
Thank you for providing your expertise with the world. I really enjoy reading your website.
Reading your blog posts feels like attending a valuable masterclass.
Hey very nice blog!
It’s great to see an author passionate about their field.
Your writing is valuable, I’ve learnt so much from it.
I’m definitely going to share this write-up with my friends and followers.
Your specialized knowledge is evident in this write-up; I’m impressed.
This article has broadened my horizons to a whole new angle; thank you.
Thank you for taking the time to research and compile such helpful knowledge.
Your blog has become one of my favorite resources. I can’t wait for new posts.
Good day I am so thrilled I found your weblog, I really
found you by accident, while I was looking on Askjeeve for something
else, Nonetheless I am here now and would just like to say thanks a lot for a incredible post and a
all round exciting blog (I also love the theme/design),
I don’t have time to browse it all at the moment but I have bookmarked it
and also included your RSS feeds, so when I have time I will be back to read a great deal more, Please do keep up the superb work.
Your blog consistently engrosses me throughout. I simply stop reading without absorbing every individual word you write.
This blogging approach is outstanding. I enjoy how you present information in a clear and manner.