我跟随"Fluent Python“来学习功能和设计模式:
在第6章中示例-代码/策略
def bulk_item_promo(order):
"""10% discount for each LineItem with 20 or more units"""
discount = 0
for item in order.cart:
if item.quantity >= 20:
discount += item.total() * .1 #augmented += ?
return discount我对以下问题感到非常困惑:
discount += item.total() * .1我想这在头顶上很复杂,因为
discount = item.total() * .1然而,作者更倾向于这样说:
discount = 0*1 + 0*2 + 0*3 + item.total() * .1人为地增加它的复杂性。
我错过了什么关键点?你能给我一些提示吗?
发布于 2018-09-11 23:24:06
代码discount += item.total() * .1等效于:
discount = discount + (item.total() * 0.1)为了清楚起见,我添加了括号,但它们不是必要的,因为乘法优先于加法。
您的函数通过将数量大于20的所有项目的折扣汇总起来计算绝对折扣。该折扣相当于范围内项目未折扣成本的10%。
也可以用sum和生成器表达式编写相同的函数:
def bulk_item_promo(order):
"""10% discount for each LineItem with 20 or more units"""
return sum(item.total() * 0.1 for item in order.cart if item.quantity >= 20)发布于 2018-09-11 23:26:31
假设顺序中有3项。称它们为a、b和c,假设每个单位有20多个单元。说吧,a.total() == b.total() == c.total() == 100。在以下情况下:
discount = item.total() * .1discount将是10。这样你就可以把10从整个300上拿掉。但这并不是你真正想要的,你想要10从每个a.total(),b.total()和c.total(),所以你想要30。这就是为什么您使用+=的原因,因为它聚集在每个(限定)项上。
发布于 2018-09-11 23:29:04
篮子里的每一件东西都可以打折。要计算总折扣,您需要将所有有折扣的项目的折扣相加,这就是代码所做的。调用变量"total_discount“而不是”折扣“可能会更好。
left += right意思是:计算“右”值,然后将其添加到左变量中。discount_total += (项目折扣公式)是指根据公式计算项目折扣,并将其添加到discount_total中。在你的情况下
discount_total += item.total() * 0.1意思是:计算这个项目的折扣率,计算它的总数并乘以0.1 (这等于取10%)。然后将此项目的折扣加到折扣总额中。
https://stackoverflow.com/questions/52285351
复制相似问题