1. ホーム
  2. python

[解決済み] Python初級編。AttributeError: 'list' オブジェクトは属性を持ちません。

2022-03-04 21:38:10

質問

というエラーが出ています。

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

違いは、あなたの bikes ディクショナリでは、リストとして値を初期化しています。 [...] . 代わりに、あなたのコードの残りの部分が望んでいるように見えます。 Bike インスタンスを作成します。 そこで Bike インスタンスを作成します。 Bike(...) .

エラーについて

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

を呼び出そうとしたときに発生します。 .cost の上で list オブジェクトを作成します。 とても簡単ですが、何が起こったかは、あなたが .cost -- この行の中で

profit = bike.cost * margin

これは、少なくとも1つの bike (のメンバー)。 bikes.values() はリストです)。 を定義したところを見てみると bikes を見ると、その値は実際にはリストであることがわかります。 ですから、このエラーは理にかなっています。

しかし あなたのクラス にはcost属性があるので、それを使おうとしているように見えました。 Bike のインスタンスを値として使用できるように、ちょっとした変更を加えました。

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

で完了です。