class Item:
def __init__(self, name, price, kind):
self.name = name
self.price = price
self.kind = kind
def getPrice(self):
return self.price
def getName(self):
return self.name
def getKind(self):
return self.kind
class Cart:
def __init__(self):
self.list = []
pass
def addItem(self, item):
self.list.append(item)
def getTotalsByKind(self, kind):
total = 0
for i in self.list:
if i.getKind() == kind:
total += i.getPrice()
t = '{:.2f}'.format(total)
print "The total for %s items is %s" %(kind, t)
3 回答
您正在打印该方法的返回值。
删除方法调用print
之前的语句;.getTotalsByKind()
该方法本身完成所有打印。
您的方法没有显式return
声明,这意味着使用默认返回值None
:
>>> def foo():
... # Nothing is returned in this function
... print 'Bar!'
...
>>> print foo()
Bar!
None
>>> foo()
Bar!
更好的选择是让您的方法返回要打印的字符串:
def getTotalsByKind(self, kind):
total = 0
for i in self.list:
if i.getKind() == kind:
total += i.getPrice()
t = '{:.2f}'.format(total)
return "The total for %s items is %s" %(kind, t)
现在您可以使用返回的字符串做不同的事情,而不仅仅是打印它。
您应该getTotalsByKind
返回字符串,而不是打印它。为此,请制作以下行:
print "The total for %s items is %s" %(kind, t)
像这样:
return "The total for %s items is %s" %(kind, t)
现在,当您打印 的结果时getTotalsByKind
,它将起作用。
默认情况下,None
如果函数结束而不返回,则返回。而且,通过使用print
with getTotalsByKind
(你必须这样做),你告诉 Python 打印 的返回值getTotalsByKind
,即None
.
您没有显示这部分代码,但我猜您正在这样做print cart.getTotalsByKind(...)
,从而告诉 Python 打印该函数的返回值。但它不返回任何东西,因此它返回None
。相反,该方法打印总数。
您已经成为一个名称不佳的方法的牺牲品:getTotalsByKind
意味着将返回总数,但只有一个总数,并且它被打印而不是被返回。我会命名这个方法printTotalByKind
。或者命名它getTotalByKind
并让调用者进行打印(和格式化)。那么您的方法可以更简单地编写如下:
def getTotalByKind(self, kind):
return sum(item.price for item in self.list if item.kind == kind)
这与您的问题无关,但您的 getter 方法完全是多余的,可能应该删除。您已经可以通过 获取商品的价格item.price
,无需调用函数来执行相同操作的开销。密码_