如何在同一个OOP类中修改多个对象?

时间:2014-03-07 16:36:09

标签: python class oop python-2.7

我已经从我的教科书中创建了一个处理动物或Critters()的程序。 目前它只处理一个小动物。

问题是现在教科书要求我创建多个小动物,而不是在一个小动物上工作的功能,这些功能应该适用于所有小动物。

我不知道如何做到这一点。

那么,我怎样才能将参数传递给多个生物?

这是我的尝试(代码段):

Traceback (most recent call last):
  File "C:\pcrit.py", line 76, in main
    animal.eat(units)
AttributeError: 'str' object has no attribute 'eat'

^错误^

import random

class Critter(object):
    """A virtual pet."""
    def __init__(self,name):
        self.name = name
        self.boredom = random.randrange(0,30)
        self.hunger = random.randrange(0,30)
        print "A new critter is born:", self.name, "\n"

    def eat(self, food):
        food = int(food)
        self.hunger -= food
        if self.hunger < 0:
            self.hunger = 0

# main

critters = ["donkey","monkey","dog","horse"]
# make each animal into the Critter() class
for animal in critters:
    animal = Critter(animal)

units = (raw_input("How many play units? "))
for animal in critters:
    animal.eat(units)

1 个答案:

答案 0 :(得分:1)

你正在迭代

critters = ["donkey","monkey","dog","horse"]

这些是字符串,它们没有像eat这样的方法。

相反,您需要列出Critter s

critters = [Critter(name) for name in ["donkey", "monkey", "dog", "horse"]]

你在做什么:

for animal in critters:
    animal = Critter(animal)

不将新对象分配回列表critters