Question

Why does my code give me the errror Attribute error: 'list' object has no attribute 'gainWeight' ?

Class code:

class Pig():

def __init__(self, name, age, weight, value):
    self.name = name
    self.age = age
    self.weight = weight
    self.value = value

def Weight(self):
    self.weight = randrange(50,250)

def growOlder(self):
    self.age += 1

def gainWeight(self, weight):
    self.weight += 5

def runAndGainValue(self):
    self.value += 5

def __str__(self):
    a = self.name + " "
    a += str(self.age) + " "
    a += str(self.weight) + " "
    a += str(self.value) + " "
    return a

And the code in the main program:

def work_function():
    work = input("What do you want to do for work today?"
        "\nPress 1 to feed your animals"
        "\nPress 2 to take them out in the yard"
        "\nPress 3 to your animals to sleep"
        "\nPress 4 to go back to main menu.\n")
    if work == "1":
        yourfarm.printAnimals()
        print ("are all very happy to be fed and have gained some weight!\nLook at the weight now and see for yourself!")
        p.gainWeight(+5)
            #Here is where the problem lies.
        yourfarm.printAnimals()

p is a list with the items for my animals.

I can't figure out why I'm getting this error.

Was it helpful?

Solution

In your second snippet, you need to access the elements of the list, not the list itself:

for pig in p:
    pig.gainWeight(5)

OTHER TIPS

You need to loop through all your elements, and call gainWeight on them, since it is a Pig that has the method, not the list:

for pig in p:
    pig.gainWeight(5)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top