创建一个类模块,用于存储和显示来自另一个类的对象

时间:2015-04-21 18:46:22

标签: python

我正在尝试创建一个名为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

1 个答案:

答案 0 :(得分:0)

首先,如果要向动物园添加animal对象,则需要将对象作为参数传递给add_animal方法。

举个例子:

class Zoo:

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