<p>我正在为期末考试做准备,但我错过了一个测验题。我需要关于getTotal方法的大部分帮助。我需要循环浏览列表,找到每个项目的价格,将价格添加到总数中,然后返回总数。我在循环中挣扎,我不知道如何从列表中取出第二项。。[1] ??我试过很多方法,现在很沮丧。</p>
<p>如果有人愿意帮助我,那就太好了。我仍然在学习,在这方面是新的,所以对我放轻松,但我真的想学习它。可能没有我想象的那么难,但我会等待一些意见。谢谢您!</p>
<pre><code>class Item:
def __init__(self, name, price):
self.name = name
self.price = price
def getPrice(self):
return self.price
def getName(self):
return self.name
class Cart:
def __init__(self, list):
self.list = []
def addItem(self, item):
self.list.<a href="https://www.cnpython.com/list/append" class="inner-link">append</a>(self.list)
def getTotal(self):
total = 0
for item in self.list:
name, price = item # or price = item[1]
total = total + price
def getNumItems(self):
count = 0
for c in range(self.list):
count = self.list + 1
return count
def removeItem(self, item)
#removes the item from the cart's item list
def main():
item1 = Item("Banana", .69)
item2 = Item("Eggs", 2.39)
item3 = Item("Donut", .99)
c = Cart()
c.addItem(item1)
c.addItem(item2)
c.addItem(item3)
print "You have %i items in your cart for a total of $%.02f" %(c.getNumItems(), c.getTotal())
c.removeItem(item3)
print "You have %i items in your cart for a total of $%.02f" % (c.getNumItems(), c.getTotal())
main()
</code></pre>
<p>对于getTotal:</p>
<pre><code>def getTotal(self):
total = 0
for item in self.list:
name, price = item # or price = item[1]
total = total + price
</code></pre>
<p>顺便说一下,addItem和getNumItems方法也是错误的。既然这是最后一次,你应该试着理解你在做什么。</p>