gpt4 book ai didi

python - 属性错误 : 'list' object has no attribute 'gainWeight'

转载 作者:行者123 更新时间:2023-11-28 20:23:36 25 4
gpt4 key购买 nike

为什么我的代码给我错误 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 是我的动物元素 list 。

我不明白为什么会出现此错误。

最佳答案

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

for pig in p:
pig.gainWeight(5)

关于python - 属性错误 : 'list' object has no attribute 'gainWeight' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19758958/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com