gpt4 book ai didi

python - 初学者 Python : AttributeError: 'list' object has no attribute

转载 作者:太空狗 更新时间:2023-10-29 16:53:30 25 4
gpt4 key购买 nike

错误说:

AttributeError: 'list' object has no attribute 'cost' 

我正在尝试使用以下类处理自行车字典来进行简单的利润计算:

class Bike(object):
def __init__(self, name, weight, cost):
self.name = name
self.weight = weight
self.cost = cost

bikes = {
# Bike designed for children"
"Trike": ["Trike", 20, 100],
# Bike designed for everyone"
"Kruzer": ["Kruzer", 50, 165]
}

当我尝试使用我的 for 语句计算利润时,出现属性错误。

# Markup of 20% on all sales
margin = .2
# Revenue minus cost after sale
for bike in bikes.values():
profit = bike.cost * margin

首先,我不知道为什么它指的是一个列表,而且一切似乎都被定义了,不是吗?

最佳答案

考虑:

class Bike(object):
def __init__(self, name, weight, cost):
self.name = name
self.weight = weight
self.cost = cost

bikes = {
# Bike designed for children"
"Trike": Bike("Trike", 20, 100), # <--
# Bike designed for everyone"
"Kruzer": Bike("Kruzer", 50, 165), # <--
}

# Markup of 20% on all sales
margin = .2
# Revenue minus cost after sale
for bike in bikes.values():
profit = bike.cost * margin
print(profit)

输出:

33.020.0

The difference is that in your bikes dictionary, you're initializing the values as lists [...]. Instead, it looks like the rest of your code wants Bike instances. So create Bike instances: Bike(...).

As for your error

AttributeError: 'list' object has no attribute 'cost'

当您尝试在 list 对象上调用 .cost 时会发生这种情况。非常简单,但我们可以通过查看调用 .cost 的位置来弄清楚发生了什么——在这一行中:

profit = bike.cost * margin

这表示至少有一个bike(即bikes.values()的成员是一个列表)。如果查看定义 bikes 的位置,您会发现这些值实际上是列表。所以这个错误是有道理的。

但是由于你的类有一个成本属性,看起来你正试图使用​​ Bike 实例作为值,所以我做了一点改变:

[...] -> Bike(...)

一切就绪。

关于python - 初学者 Python : AttributeError: 'list' object has no attribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29335423/

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