定义一个抽象快递包裹类Package, 并由此派生出普通包裹类和加急包裹类。 要求: (1) Package类设计为抽象类, 应包含寄件人和收件人姓名、 地址和包裹 重量属性; (2) 普通包裹增加首重计费和超首重后部分的的每公斤计费单价属性,按 首重+超重*每公斤计费单价计算总费用。 (3)加急包裹没有首重限制, 但有加急起价费用属性, 按加急起价费+重 量*10+加急公里数*0.02计算总费用。 (4)为每个类添加calculateCost 计算快递费用方法。编写测试程序,创建每种包裹类的对象并测试calculateCost方法
时间: 2024-04-03 07:32:05 浏览: 102
好的,这是一个简单的面向对象编程问题。下面是抽象类Package的实现:
```python
from abc import ABC, abstractmethod
class Package(ABC):
def __init__(self, sender_name, sender_address, receiver_name, receiver_address, weight):
self.sender_name = sender_name
self.sender_address = sender_address
self.receiver_name = receiver_name
self.receiver_address = receiver_address
self.weight = weight
@abstractmethod
def calculateCost(self):
pass
```
接下来是普通包裹类:
```python
class RegularPackage(Package):
def __init__(self, sender_name, sender_address, receiver_name, receiver_address, weight, first_weight_price, additional_weight_price):
super().__init__(sender_name, sender_address, receiver_name, receiver_address, weight)
self.first_weight_price = first_weight_price
self.additional_weight_price = additional_weight_price
def calculateCost(self):
if self.weight <= 1:
return self.first_weight_price
else:
additional_weight = self.weight - 1
return self.first_weight_price + additional_weight * self.additional_weight_price
```
最后是加急包裹类:
```python
class ExpressPackage(Package):
def __init__(self, sender_name, sender_address, receiver_name, receiver_address, weight, urgent_fee, urgent_distance):
super().__init__(sender_name, sender_address, receiver_name, receiver_address, weight)
self.urgent_fee = urgent_fee
self.urgent_distance = urgent_distance
def calculateCost(self):
return self.urgent_fee + self.weight * 10 + self.urgent_distance * 0.02
```
测试程序如下:
```python
# 创建普通包裹对象并计算费用
p1 = RegularPackage("张三", "北京市海淀区", "李四", "上海市浦东新区", 2.5, 20, 5)
print("普通包裹费用:", p1.calculateCost())
# 创建加急包裹对象并计算费用
p2 = ExpressPackage("王五", "广州市天河区", "赵六", "深圳市福田区", 1.5, 30, 20)
print("加急包裹费用:", p2.calculateCost())
```
输出:
```
普通包裹费用: 32.5
加急包裹费用: 45.0
```
阅读全文