我正在尝试创建一个名为Zoo.py
的类。我创建了另一个名为Animal.py
的类程序,它显示需要在另一个名为Zookeeper
的程序上打印的信息。我对Zookeeper
程序没有任何问题。
我的问题是我不知道如何使Zoo
类程序具有名为__animals
的属性,该属性将是用于存储Animal
个对象的列表。然后我将使用__init__
方法为__animals
创建一个空列表。
我将创建一个add_animal
方法,该方法将接收Animal
个对象并将其附加到__animals
列表。
然后我将创建一个show_animals
方法,用于打印Animal
内__animals
个对象的相关信息,如果没有Animal
已添加到列表中,它应该打印出一条消息,说没有Animal
s。
以下是Animals.py
程序需要从Zoo
程序获取信息的程序:
# This program defines the Animal class
import random
class Animal:
# Define what happens when a new animal object is created
def __init__(self, animal_type, animal_name):
self.__animal_type = animal_type
self.__name = animal_name
self.__mood = "happy"
# Return the animal's type
def get_animal_type(self):
return self.__animal_type
# Return the animal's name
def get_name(self):
return self.__name
# Determine and return the animal's mood
def check_mood(self):
# Pick a number between 1 and 3
random_number = random.randint(1, 3)
# Set the animal's mood based on the random number
if random_number == 1:
self.__mood = "happy"
elif random_number == 2:
self.__mood = "hungry"
elif random_number == 3:
self.__mood = "sleepy"
# Finally, return the mood
return self.__mood
到目前为止,对于Zoo
课程,这就是我所拥有的:
import Animals
class Zoo:
__animals = []
# Use method to create an empty list for __animals
def __init__(self):
self.__animals = animal_list
# Receive an Animal object and append it to the __animals list
def add_animal(self):
animal.append(animal_list)
# Determine and return the animal's mood
def show_animals(self):
return animal_list
ZooKeeper.py
我不需要任何帮助,但这是Zoo.py
工作后程序的样子:
Zoo Options
-----------
1. Add Animal
2. Show Animals
3. Exit
What would you like to do? 1
What type of animal would you like to create? Platypus
What is the animal's name? Penelope
Zoo Options
-----------
1. Add Animal
2. Show Animals
3. Exit
What would you like to do? 2
Animal List
-----------
Penelope the Platypus is sleepy
答案 0 :(得分:0)
首先,如果要向动物园添加animal
对象,则需要将对象作为参数传递给add_animal
方法。
举个例子:
class Zoo:
def add_animal(self, animal):
self.__animals.append(animal)