# 定义快递包裹类 Packageclass Package: def __init__(self, sender, receiver, sender_addr, receiver_addr, weight): self.sender = sender self.receiver = receiver self.sender_addr = sender_addr self.receiver_addr = receiver_addr self.weight = weight # 计算快递费用方法 def calculateCost(self): return self.weight * 10# 定义普通包裹类 NormalPackage,继承自 Packageclass NormalPackage(Package): def __init__(self, sender, receiver, sender_addr, receiver_addr, weight, first_weight, extra_cost): super().__init__(sender, receiver, sender_addr, receiver_addr, weight) self.first_weight = first_weight self.extra_cost = extra_cost # 计算快递费用方法 def calculateCost(self): if self.weight <= self.first_weight: return self.first_weight * self.extra_cost else: return self.first_weight * self.extra_cost + (self.weight - self.first_weight) * self.extra_cost# 定义加急包裹类 ExpressPackage,继承自 Packageclass ExpressPackage(Package): def __init__(self, sender, receiver, sender_addr, receiver_addr, weight, express_price): super().__init__(sender, receiver, sender_addr, receiver_addr, weight) self.express_price = express_price # 计算快递费用方法 def calculateCost(self): return self.express_price + self.weight * 10# 测试程序np = NormalPackage("Sender", "Receiver", "Sender Address", "Receiver Address", 15, 5, 8)ep = ExpressPackage("Sender", "Receiver", "Sender Address", "Receiver Address", 15, 20)print("普通包裹费用为:", np.calculateCost())print("加急包裹费用为:", ep.calculateCost())
时间: 2024-04-01 14:34:04 浏览: 147
这段代码定义了三个类:Package、NormalPackage和ExpressPackage,它们分别代表快递包裹、普通包裹和加急包裹。其中,NormalPackage和ExpressPackage都继承自Package,即它们都是Package的子类。
在Package类中,定义了一个构造函数__init__()和一个计算快递费用的方法calculateCost()。在__init__()中,初始化了sender、receiver、sender_addr、receiver_addr和weight等属性。在calculateCost()中,根据weight计算出快递费用,每公斤10元。
在NormalPackage类中,除了继承自Package类的属性和方法外,还定义了first_weight和extra_cost属性,用于计算快递费用。在calculateCost()中,如果weight小于等于first_weight,则只需支付first_weight * extra_cost元;否则需要支付first_weight * extra_cost加上(weight - first_weight) * extra_cost元。
在ExpressPackage类中,除了继承自Package类的属性和方法外,还定义了express_price属性,表示加急费用。在calculateCost()中,需要支付express_price元的加急费用加上weight * 10元的快递费用。
最后,测试程序创建了一个NormalPackage对象np和一个ExpressPackage对象ep,并调用它们的calculateCost()方法计算快递费用。
阅读全文