背景
在计算机专业面试中,面试官往往会针对者的实际操作能力和解决能力进行考察。是一道典型的业务上BUG旨在测试者对业务逻辑和代码调试的掌握程度。
“假设你正在开发一个在线书店的购物车功能,用户可以添加、删除商品,并计算总金额。是一个简单的购物车类实现,存在一个BUG,请找出并修复它。”
python
class ShoppingCart:
def __init__(self):
self.items = []
self.total = 0
def add_item(self, item, price):
self.items.append(item)
self.total += price
def remove_item(self, item):
for i, cart_item in enumerate(self.items):
if cart_item == item:
self.total -= cart_item.price
del self.items[i]
return
def get_total(self):
return self.total
# 示例使用
cart = ShoppingCart()
cart.add_item({'name': 'Book', 'price': 12.99})
cart.add_item({'name': 'Pen', 'price': 1.99})
print("Total before removal:", cart.get_total())
cart.remove_item({'name': 'Book', 'price': 12.99})
print("Total after removal:", cart.get_total())
分析
在这段代码中,我们需要注意几个关键点:
1. `add_item` 方法添加商品到购物车,并更新总金额。
2. `remove_item` 方法删除商品,并从总金额中减去相应商品的价格。
3. 在 `remove_item` 方法中,我们通过遍历 `items` 列表来找到并删除指定商品。
在于,当我们删除商品时,我们没有正确地从总金额中减去商品的价格。`remove_item` 方法中存在一个它没有正确地访问到被删除商品的 `price` 属性。
解答
要修复这个我们需要确保在删除商品时能够正确地访问到它的 `price` 属性。是修复后的代码:
python
class ShoppingCart:
def __init__(self):
self.items = []
self.total = 0
def add_item(self, item, price):
self.items.append({'name': item, 'price': price})
self.total += price
def remove_item(self, item):
for cart_item in self.items:
if cart_item['name'] == item:
self.total -= cart_item['price']
self.items.remove(cart_item)
return
def get_total(self):
return self.total
# 示例使用
cart = ShoppingCart()
cart.add_item('Book', 12.99)
cart.add_item('Pen', 1.99)
print("Total before removal:", cart.get_total())
cart.remove_item('Book')
print("Total after removal:", cart.get_total())
在修复后的代码中,我们在 `add_item` 方法中创建了一个包含 `name` 和 `price` 属性的字典来表示商品。这样,在 `remove_item` 方法中,我们可以通过比较 `name` 属性来找到正确的商品,并从总金额中减去它的 `price`。
通过这道面试题,我们可以看到,解决不仅仅是找到BUG,更重要的是理解的根本原因,并采取正确的措施进行修复。在开发过程中,细心和耐心是必不可少的。良代码风格和注释也是确保代码可读性和可维护性的关键。
还没有评论呢,快来抢沙发~