0

I have a parent class:

class Animal(object):

    animalFoods = {'Elephant': ['Grass', 'Trees'], 'Turtle': 'Fish'}

    def animal_food(self):
        foods = Animal.animalFoods[self.__class__.__name__]
        for food in foods:
            return food

Then I have a subclass:

class Elephant(Animal):
    pass

I create an object:

Dumbo = Elephant()

And try to print out its food choice:

>>> print(Dumbo.animal_food())
Grass

I expect it to print out

Grass
Trees

I see how it is working by finding the key in the animalFoods dictionary, but I am not sure why it is not returning both values in the value list.

Pointers towards additional reading are appreciated over just providing a quick and dirty answer, as this is my first time working with dictionaries beyond single values.

Tonechas
  • 13,398
  • 16
  • 46
  • 80
Drew Ackerman
  • 241
  • 2
  • 14
  • Since you have already have the list of food `foods = Animal.animalFoods[self.__class__.__name__]`, there is no need to iterate that list. Besides, if you want to print items in list, you could have a look at [Pythonic way to print list items](http://stackoverflow.com/questions/15769246/pythonic-way-to-print-list-items). Or if you want to iterate the list, the reason that you stop at the half way is, as pointed by @Alex, is terminated by 'return' – Shawn. L Jun 22 '16 at 04:57
  • Thank you for the additional helpful link :) – Drew Ackerman Jun 22 '16 at 05:00

3 Answers3

3

return food will immediately end execution of your animal_food; it will not attempt to complete the loop. If you wanted to get very fancy, you could use yield food to turn the method into a generator, but probably for this example you just want to replace the method body completely:

def animal_food(self):
    return Animal.animalFoods[self.__class__.__name__]
Alex Taylor
  • 8,343
  • 4
  • 25
  • 40
0

Please see here:

foods = Animal.animalFoods[self.__class__.__name__]
for food in foods:
    return food

for foods, it is right, which is ['Grass', 'Trees'].

But you do for food in foods: return food. the return just return the for loop, so you get one result.

BlackMamba
  • 10,054
  • 7
  • 44
  • 67
0

Once a function or a method returns a value the for loop execution will halt.

If you merely wanted to print the items you could add the print statement to the class method animal_food() like this:

def animal_food(self):
  foods = Animal.animalFoods[self.__class__.__name__]
  for food in foods:
    print food

Then, calling Dumbo.animal_food() would print both answers.

Carl Lane
  • 66
  • 5