背景
在计算机专业的面试中,面试官往往会提出一些具有挑战性的以考察者的实际编程能力和解决能力。业务上BUG一条是一种常见题型。这类要求者不仅能够找出代码中的错误,还要能够解释错误的原因,并提出有效的解决方案。是一道典型的业务上BUG一条的面试题及解答。
面试题
假设你正在开发一个电商平台的购物车功能。用户可以在购物车中添加商品,查看商品数量和总价,以及进行结算。是一个简化版的购物车类实现,请找出的BUG,并解释原因。
python
class ShoppingCart:
def __init__(self):
self.items = []
self.quantity = 0
self.total_price = 0
def add_item(self, item, price):
self.items.append(item)
self.quantity += 1
self.total_price += price
def remove_item(self, item):
if item in self.items:
self.items.remove(item)
self.quantity -= 1
self.total_price -= self.get_price(item)
def get_price(self, item):
for product in self.items:
if product == item:
return product.price
return 0
def get_total_price(self):
return self.total_price
分析与解答
我们注意到`get_price`方法中的逻辑。这个方法尝试在`self.items`列表中查找与传入的`item`相匹配的商品,并返回该商品的价格。这里存在一个商品对象应该有一个属性来存储价格,而不是直接在商品对象中使用`price`变量。
是代码中存在的及原因:
1. `get_price`方法中,商品对象没有明确的`price`属性,而是直接使用`product.price`。这可能导致`AttributeError`,商品对象没有定义`price`属性。
2. 当从购物车中移除商品时,`remove_item`方法应该确保从`self.items`中移除正确的商品对象。商品对象是使用相同的实例创建的,则可能不会按预期移除商品。
3. `add_item`方法中,`self.quantity`和`self.total_price`的更新应该使用局部变量来存储当前的商品数量和总价,以避免在添加多个商品时重复计算。
针对上述是修正后的代码:
python
class ShoppingCart:
def __init__(self):
self.items = []
self.quantity = 0
self.total_price = 0
def add_item(self, item, price):
self.items.append(item)
self.quantity += 1
self.total_price += price
def remove_item(self, item):
for i, product in enumerate(self.items):
if product == item:
self.items.pop(i)
self.quantity -= 1
self.total_price -= product.price
break
def get_price(self, item):
for product in self.items:
if product == item:
return product.price
return 0
def get_total_price(self):
return self.total_price
在修正后的代码中,我们对`remove_item`方法进行了修改,使其能够正确地移除匹配的商品对象。我们确保在`add_item`和`remove_item`方法中,商品的价格是通过`product.price`获取的,这样就不会因为商品对象没有定义`price`属性而导致错误。
通过分析上述我们不仅找到了代码中的BUG,还学会了如何正确地处理商品对象的价格和数量更新。在面试中,这类能够考察者对编程细节的关注程度,以及对解决方法的思考能力。对于者来说,理解背后的逻辑,并提出清晰的解决方案是至关重要的。
还没有评论呢,快来抢沙发~