一、背景与
在计算机专业的面试中,业务上BUG一条是一种常见的题型。这类往往要求面试者能够根据提供的代码片段或者业务场景,找出的错误,并给出解决方案。下面,我们就来分析一个具体的业务上BUG一条并探讨解题思路。
假设有一个在线购物系统,用户可以通过该系统查看商品信息、添加购物车、提交订单等功能。是一个购物车功能的代码片段,请找出的BUG,并说明原因。
python
class ShoppingCart:
def __init__(self):
self.items = []
def add_item(self, item):
if item not in self.items:
self.items.append(item)
def remove_item(self, item):
if item in self.items:
self.items.remove(item)
def get_total_price(self):
total_price = 0
for item in self.items:
total_price += item.price
return total_price
# 示例用法
cart = ShoppingCart()
cart.add_item(Product("Laptop", 1200))
cart.add_item(Product("Smartphone", 800))
print("Total Price:", cart.get_total_price())
二、BUG分析与解题思路
在上述代码中,我们定义了一个`ShoppingCart`类,它有三个方法:`add_item`用于添加商品到购物车,`remove_item`用于从购物车中移除商品,`get_total_price`用于计算购物车中所有商品的总价。
通过阅读代码,我们可以发现BUG:
1. `add_item`方法中没有对`item`参数进行类型检查,导致可能添加非商品对象到购物车。
2. `remove_item`方法中,`item`参数的类型没有明确指定,可能存在类型错误。
3. `get_total_price`方法中,假设了所有商品都有一个`price`属性,但没有检查这个属性是否存在于商品对象中。
解题思路如下:
1. 在`add_item`和`remove_item`方法中,增加类型检查,确保只有商品对象可以被添加或移除。
2. 在`get_total_price`方法中,对每个商品对象进行属性检查,确保它们都有`price`属性。
三、修改后的代码与答案
下面是修改后的代码,包含了对BUG的修复:
python
class ShoppingCart:
def __init__(self):
self.items = []
def add_item(self, item):
if isinstance(item, Product) and item not in self.items:
self.items.append(item)
def remove_item(self, item):
if isinstance(item, Product) and item in self.items:
self.items.remove(item)
def get_total_price(self):
total_price = 0
for item in self.items:
if hasattr(item, 'price'):
total_price += item.price
else:
raise AttributeError("Item does not have a 'price' attribute.")
return total_price
# 示例用法
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
cart = ShoppingCart()
cart.add_item(Product("Laptop", 1200))
cart.add_item(Product("Smartphone", 800))
print("Total Price:", cart.get_total_price())
在修改后的代码中,我们对`add_item`和`remove_item`方法增加了类型检查,确保只有`Product`类的实例可以被添加或移除。在`get_total_price`方法中,我们检查了每个商品对象是否有`price`属性,没有,则抛出`AttributeError`。
这样,我们就成功修复了原始代码中的BUG,并提供了相应的解决方案。在面试中,这样的能够考察面试者对代码细节的关注程度以及解决的能力。
还没有评论呢,快来抢沙发~