<p>我可以建议一个更简单的课堂设计吗。你知道吗</p>
<ul>
<li><p><code>my_item</code>保持原样,其他类<code>fruit, vegetable etc</code>。已删除</p></li>
<li><p>对<code>shopping_cart</code>进行修改,使得<code>self.items</code>是一个字典,其中键是项的名称<code>fruit, vegetables</code>,值是这些项的列表</p></li>
</ul>
<p>那么代码可能如下所示</p>
<pre><code>import csv
from collections import defaultdict
class my_item:
def __init__(self, name):
self.name = name
class shopping_cart:
def __init__(self):
#Dictionary to hold items
self.items = defaultdict(list)
def add_item(self, type, name):
#Increment the count of the item by 1
self.items[type].append(name)
def __str__(self):
#Iterate through the dictionary and print all key/value pairs
msg = ""
for k,v in self.items.items():
msg += ' {}: {} '.format(k, v)
return msg.strip()
sc = shopping_cart()
sc.add_item('fruit', 'pomme')
sc.add_item('vegetable', 'dinde')
sc.add_item('meat', 'carotte')
sc.add_item('fish', 'saumon')
print(sc)
</code></pre>
<p>输出看起来像</p>
<pre><code>fruit: ['pomme'] vegetable: ['dinde'] meat: ['carotte'] fish: ['saumon']
</code></pre>