2

为什么我的代码会给我错误Attribute error: 'list' object has no attribute 'gainWeight'

班级代码:

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

以及主程序中的代码:

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 是我的动物物品的列表。

我不知道为什么我会收到这个错误。

4

2 回答 2

4

在您的第二个片段中,您需要访问列表的元素,而不是列表本身:

for pig in p:
    pig.gainWeight(5)
于 2013-11-03T22:27:54.223 回答
4

您需要遍历所有元素并调用gainWeight它们,因为它Pig具有方法,而不是列表:

for pig in p:
    pig.gainWeight(5)
于 2013-11-03T22:28:28.883 回答