【发布时间】:2014-03-07 16:36:09
【问题描述】:
我根据教科书创建了一个程序,用于处理动物或Critters()。
目前它只处理一个小动物。
现在的问题是教科书要求我创建多个小动物,而不是函数对单个小动物起作用,而函数应该对所有小动物起作用。
我对如何做到这一点一无所知。
那么,如何将参数传递给多个小动物?
这是我的尝试(code sn-p):
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)
【问题讨论】:
标签: python class oop python-2.7