面试题答案
一键面试设计思路
在大型复杂Python系统中,不同模块可能有相似但又不完全相同的行为。通过抽象类和抽象方法,可以将这些共性行为抽象出来,使得具体模块只需要关注自身特有的实现,从而解耦模块。这样做提高了代码的可维护性,因为当共性行为需要修改时,只需要在抽象类中修改一处;同时也增强了扩展性,新的模块可以通过继承抽象类来快速融入系统。
主要抽象类和抽象方法定义
假设我们有一个电商系统,其中有不同类型的商品,如电子产品、服装等,它们都需要计算价格和获取描述信息,但具体计算和描述方式不同。我们可以定义一个抽象商品类 AbstractProduct
,包含抽象方法 calculate_price
和 get_description
。
from abc import ABC, abstractmethod
class AbstractProduct(ABC):
@abstractmethod
def calculate_price(self):
pass
@abstractmethod
def get_description(self):
pass
系统中的交互流程
- 具体的商品类(如
ElectronicProduct
和ClothingProduct
)继承自AbstractProduct
抽象类。 - 系统的其他部分(如订单模块)可以通过
AbstractProduct
类型来操作不同的商品,而不需要关心具体的商品类型。这样,当添加新的商品类型时,订单模块的代码不需要修改。
代码示例
class ElectronicProduct(AbstractProduct):
def __init__(self, price, brand):
self.price = price
self.brand = brand
def calculate_price(self):
# 电子产品可能有品牌折扣
if self.brand == "Apple":
return self.price * 0.95
return self.price
def get_description(self):
return f"Electronic product: {self.brand}, price: {self.calculate_price()}"
class ClothingProduct(AbstractProduct):
def __init__(self, price, size):
self.price = price
self.size = size
def calculate_price(self):
# 服装可能有尺码相关的价格调整
if self.size == "XL":
return self.price * 1.1
return self.price
def get_description(self):
return f"Clothing product: size {self.size}, price: {self.calculate_price()}"
# 订单模块,处理不同类型商品
class Order:
def __init__(self):
self.products = []
def add_product(self, product):
self.products.append(product)
def calculate_total(self):
total = 0
for product in self.products:
total += product.calculate_price()
return total
def get_order_description(self):
descriptions = []
for product in self.products:
descriptions.append(product.get_description())
return "\n".join(descriptions)
# 使用示例
order = Order()
electronic = ElectronicProduct(1000, "Apple")
clothing = ClothingProduct(200, "XL")
order.add_product(electronic)
order.add_product(clothing)
print(order.calculate_total())
print(order.get_order_description())
在上述代码中,AbstractProduct
抽象类定义了所有商品类共有的抽象方法。ElectronicProduct
和 ClothingProduct
具体类继承自 AbstractProduct
并实现了抽象方法。Order
类通过 AbstractProduct
类型来处理不同的商品,从而实现了模块间的解耦,提高了代码的可维护性和扩展性。