新手总数。。。需要帮助了解python类吗

2024-10-05 12:23:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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)

Tags: 实例方法代码self信息inputmytype
3条回答

直接回答:

class Zoo(object):
    def __init__(self, name="Python Zoo"):
        self.name = name
        self.animals = list()

    def getAnimal(self,index):
        index = index - 1 # account for zero-indexing
        try:
            print("Animal is {0.name}\n  Diet: {0.diet}\n  Habitat: {0.habitat}".format(
                self.animals[index]))
        except IndexError:
            print("No animal at index {}".format(index+1))

    def listAnimals(self,index):
        for i,animal in enumerate(self.animals, start=1):
            print("{i:>3}: {animal.name}".format(i=i,animal=animal))


class Animal(object):
    def __init__(self, name=None, diet=None, habitat=None):
        if any([attr is None for attr in [name,diet,habitat]]):
            raise ValueError("Must supply values for all attributes")
        self.name = name
        self.diet = diet
        self.habitat = habitat


class ZooDriver(object):
    def __init__(self):
        self.zoo = Zoo()
        self.zoo.animals = [Animal(name="Giraffe", diet="Herbivore", habitat="Outside"),
                            Animal(name="Lion", diet="Carnivore", habitat="Inside"),
                            Animal(name="Bear", diet="Herbivore", habitat="Inside")]

    def run(self):
        while True:
            print("1. List Animals")
            print("2. Get information about an animal (by index)"
            print("3. Quit")
            input_correct = False
            while not input_correct:
                in_ = input(">> ")
                if in_ in ['1','2','3']:
                    input_correct = True
                    {'1':self.zoo.listAnimals,
                     '2':lambda x: self.zoo.getAnimal(input("index #: ")),
                     '3': self.exit}[in_]()
                else:
                    print("Incorrect input")
    def exit(self):
        return

if __name__ == "__main__":
    ZooDriver().run()

我并没有实际运行过这段代码,所以可能会出现一些愚蠢的打字错误和常见的“逐个关闭”错误(oops),但我对它相当有信心。它显示了许多你的指导老师不希望你掌握的概念(比如字符串格式,很可能,几乎肯定是用lambdas的哈希表)。因此,我强烈建议您不要复制此代码来上缴。在

类定义了事物的类型。实例就是那种类型的东西。例如,您可以说Building是一种类型的东西。在

让我们从一个名为Building的类开始:

class Building():
    pass

现在,要创建一个实际的构建实例,我们将其称为函数:

^{pr2}$

在那里,我们刚刚建造了三座建筑。它们是相同的,这不是很有用。也许我们可以在创建它时给它一个名称,并将它存储在一个实例变量中。这需要创建一个接受参数的构造函数。所有类方法还必须将self作为其第一个参数,因此我们的构造函数将采用两个参数:

class Building():
    def __init__(self, name):
        self.name = name

现在我们可以创建三个不同的建筑:

b1 = Building("firehouse")
b2 = Building("hospital")
b3 = Building("church")

如果我们想创建一个“driver”类来创建三个建筑,我们可以很容易地做到这一点。如果您想在创建实例时设置实例变量或执行一些工作,可以在构造函数中执行此操作。例如,这将创建这样一个类,该类创建三个建筑并将它们存储在一个数组中:

class Town():
    def __init__(self):
        self.buildings = [
            Building("firehouse"),
            Building("hospital"),
            Building("church")
        ]

我们现在可以创建一个单独的对象来创建其他三个对象。希望这足以让你克服理解类的最初障碍。在

好的,我将试着回答这里的主要问题:什么是类。在

From Google: class /klas/
             noun: class; plural noun: classes

1.
a set or category of things having some property or attribute in common and
differentiated from others by kind, type, or quality.

在编程中,类就是这样。比如说,你有班狗。狗叫“ruf ruff”。在

我们可以仅使用这些信息在python中定义dog类。在

^{pr2}$

要使用该类,它是instantiated,方法是调用()其构造函数:

Spot = Dog()

然后我们想让Spot吠叫,所以我们调用类的method

Spot.bark()

在这里进一步解释代码的细节就超出了这个问题的范围。在

进一步阅读:

http://en.wikipedia.org/wiki/Instance_%28computer_science%29

http://en.wikipedia.org/wiki/Method_%28computer_programming%29

相关问题 更多 >

    热门问题