【问题标题】:Beginner Python: AttributeError: 'list' object has no attribute初学者 Python:AttributeError:'list' 对象没有属性
【发布时间】:2015-06-02 19:57:45
【问题描述】:

错误提示:

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

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

【问题讨论】:

  • 您没有使用[] 语法创建Bike 对象。您正在创建列表。

标签: python list class dictionary attributeerror


【解决方案1】:

考虑:

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'

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

profit = bike.cost * margin

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

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

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

一切就绪。

【讨论】:

  • 如果您解释了您的代码和 OP 之间的区别,这将是一个更好的答案。
  • @Kevin 在我发布后对其进行了编辑——实际上是要再次修改它以解释最初的错误。
【解决方案2】:

它们是列表,因为您在字典中将它们作为列表键入:

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

【讨论】:

    【解决方案3】:

    在这样使用之前,您需要将 dict 的值传递给 Bike 构造函数。或者,请参阅 namedtuple -- 似乎更符合您的目标。

    【讨论】:

      猜你喜欢
      • 2015-09-02
      • 2016-06-26
      • 2016-11-08
      • 2014-04-26
      • 2021-01-15
      • 2020-03-09
      • 2013-05-14
      • 2011-12-02
      相关资源
      最近更新 更多