0

I have created a program from my textbook that deals with animals or Critters(). At the moment it deals with only a single critter.

The problem is now the textbook has asked me to create multiple critters, and instead of the functions working on a single critter, the functions should instead work on all of the critters.

I have zero idea how to do this.

So, how can I pass arguments to the multiple critters?

Here's my attempt (code snippet):

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

^error^

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 Answer 1

1

You are iterating through

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

Those are strings, they don't have methods like eat.

Instead, you need to make a list of Critters

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

What you are doing:

for animal in critters:
    animal = Critter(animal)

Doesn't assign the new objects back to the list critters.

Sign up to request clarification or add additional context in comments.

8 Comments

I don't understand why iterating through the list doesn't work. It works manually if I type donkey.eat(units)
@user2071506 yes, but you aren't putting the Critter instance back into the list, so you always iterate over the strings.
@JonClements where would I be without you!
@jonrsharpe someone said that earlier in Python chat :)... my response remains the same - "you'd be left in peace" :p
@jonrsharpe Oh, I think I understand... So you mean the For loop is literally doing this: "donkey".eat(units)? I don't fully understand the code in your answer, so I'm trying to work it out in my head more for an easier solution.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.