Reputation: 21
I want to use a method that I made within a class on a list of animals but I am unsure of how to do so.
I've tried calling the method on the list, but I guess because the method is within my class it can't identify it.
from src.ruminant import Ruminant
class Goat(Ruminant):
def __init__(self, age):
Ruminant.__init__(self, age)
def make_sound(self):
return Ruminant.make_sound(self) + " - baah"
#in another program vvv
animals = [Goat(2.0), Goat(2.1)]
This is just an example because I want to try to do some on my own, but I am unsure of how to make it output baah baah. Any help would be much appreciated and if I haven't worded this whole question well I am happy to try to further explain.
Upvotes: 2
Views: 64
Reputation: 7998
Be sure you understand and can explain what a method is, specifically the notion that a method is fundamentally part of a class. When you write this:
animal = Goat(2.0)
You create a Goat object, sometimes referred to as an instance the Goat class, and assign it to the name animal
. Once you have an object, you can call the methods that are defined for it:
animal.make_sound()
In Python, the square brackets []
are used to define a special data structure called a list. When you type:
animals = [Goat(2.1), Goat(2.2)]
you are creating two separate goat instances, and storing them in a list. The list is assigned the name animals
, and can be accessed using special syntax.
Items in a list have an index number, which can be used to access individual members. This is how you would access the first object in the list:
animals[0]
Note that most programming languages are zero indexing meaning they start at index 0
. So the second object in the list would be:
animals[1]
Just like before, we can call methods that are defined for items in the list:
animals[0].make_sound()
animals[1].make_sound()
Once you understand how that works, it makes sense to ask "what if I don't know how many animals there are in a list?" And in that case, you need to recognize that, for each animal in your list, you would be performing the same operation: calling make_sound()
. If you wanted to call that method on a list with any number of animals, you could do it like this:
for animal in animals:
animal.make_sound()
Upvotes: 0
Reputation: 71620
After you have the list:
animals = [Goat(2.0), Goat(2.1)]
Just do :
for animal in animals:
animal.make_sound()
Upvotes: 7