错误提示:

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.0
20.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'

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

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

但是,由于您的类具有cost属性,因此您似乎想将Bike实例用作值,所以我做了一点改动:
[...] -> Bike(...)

你们都准备好了。

10-07 21:52