我对python的理解是零比零。。。我一直在读各种各样的方法来达到这个目的。下面我把作业描述和我的代码。。。到目前为止,我在使用'getAnimal()'命令时遇到问题。我不知道它是做什么的,它是如何工作的。提前感谢:D
作业描述:“为一个类‘Zoo’编写一个类定义,它应该有动物类型、食草动物/食肉动物/杂食动物和内部/外部的实例变量。它还应该有一个getAnimal()方法来显示动物信息。编写一个单独的“ZooDriver”类,以a)创建动物园动物的三个实例,b)获取用户输入的要查看的动物信息(1,2,3)c)显示动物信息起诉getAnimal()
~~~~~~~我的代码:
class Zoo:
def __init__(self, animal, animal_type, habitat):
self.animal = animal
self.animal_type = animal_type
self.habitat = habitat
user_input=raw_input("Enter the number 1, 2, or 3 for information on an animal.")
if user_input == "1":
my_animal = Zoo("Giraffe", "herbivore", "outside")
elif user_input == "2":
my_animal = Zoo("Lion", "carnivore", "inside")
elif user_input == "3":
my_animal = Zoo("Bear", "omnivore", "inside")
print "Your animal is a %s, it is a %s, and has an %s habitat." % (my_animal.animal, my_animal.animal_type, my_animal.habitat)
直接回答:
我并没有实际运行过这段代码,所以可能会出现一些愚蠢的打字错误和常见的“逐个关闭”错误(oops),但我对它相当有信心。它显示了许多你的指导老师不希望你掌握的概念(比如字符串格式,很可能,几乎肯定是用lambdas的哈希表)。因此,我强烈建议您不要复制此代码来上缴。在
类定义了事物的类型。实例就是那种类型的东西。例如,您可以说
Building
是一种类型的东西。在让我们从一个名为
Building
的类开始:现在,要创建一个实际的构建实例,我们将其称为函数:
^{pr2}$在那里,我们刚刚建造了三座建筑。它们是相同的,这不是很有用。也许我们可以在创建它时给它一个名称,并将它存储在一个实例变量中。这需要创建一个接受参数的构造函数。所有类方法还必须将
self
作为其第一个参数,因此我们的构造函数将采用两个参数:现在我们可以创建三个不同的建筑:
如果我们想创建一个“driver”类来创建三个建筑,我们可以很容易地做到这一点。如果您想在创建实例时设置实例变量或执行一些工作,可以在构造函数中执行此操作。例如,这将创建这样一个类,该类创建三个建筑并将它们存储在一个数组中:
我们现在可以创建一个单独的对象来创建其他三个对象。希望这足以让你克服理解类的最初障碍。在
好的,我将试着回答这里的主要问题:什么是类。在
在编程中,类就是这样。比如说,你有班狗。狗叫“ruf ruff”。在
我们可以仅使用这些信息在python中定义dog类。在
^{pr2}$要使用该类,它是
instantiated
,方法是调用()
其构造函数:然后我们想让Spot吠叫,所以我们调用类的
method
:在这里进一步解释代码的细节就超出了这个问题的范围。在
进一步阅读:
http://en.wikipedia.org/wiki/Instance_%28computer_science%29
http://en.wikipedia.org/wiki/Method_%28computer_programming%29
相关问题 更多 >
编程相关推荐