错误说:
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]
}
当我尝试用my语句计算利润时,我得到了属性错误。
# Markup of 20% on all sales
margin = .2
# Revenue minus cost after sale
for bike in bikes.values():
profit = bike.cost * margin
首先,我不知道为什么它会引用一个列表,一切似乎都被定义了,不是吗?
答案 0 :(得分:17)
考虑:
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.0 20.0
不同之处在于,在bikes
词典中,您将值初始化为列表[...]
。相反,您的代码的其余部分看起来像Bike
个实例。因此,请创建Bike
个实例:Bike(...)
。
至于你的错误
AttributeError: 'list' object has no attribute 'cost'
当您尝试在.cost
对象上调用list
时会发生这种情况。非常简单,但我们可以通过查看您调用.cost
的位置来弄清楚发生了什么 - 在这一行:
profit = bike.cost * margin
这表示至少有一个bike
(即bikes.values()
的成员是一个列表)。如果您查看定义的位置bikes
,您可以看到这些值实际上是列表。所以这个错误是有道理的。
但是由于你的类有一个cost属性,看起来你试图使用Bike
个实例作为值,所以我做了一点改变:
[...] -> Bike(...)
你已经完成了。
答案 1 :(得分:4)
在使用之前,您需要将dict的值传递给Bike
构造函数。或者,请参阅namedtuple
- 似乎更符合您的目标。
答案 2 :(得分:4)
它们是列表,因为您将它们键入字典中的列表:
bikes = {
# Bike designed for children"
"Trike": ["Trike", 20, 100],
# Bike designed for everyone"
"Kruzer": ["Kruzer", 50, 165]
}
你应该使用自行车类:
bikes = {
# Bike designed for children"
"Trike": Bike("Trike", 20, 100),
# Bike designed for everyone"
"Kruzer": Bike("Kruzer", 50, 165)
}
这样您就可以在尝试使用bike.cost时获得自行车的费用。
for bike in bikes.values():
profit = bike.cost * margin
print(bike.name + " : " + str(profit))
现在将打印:
Kruzer : 33.0
Trike : 20.0