假定居民的基本数据包括身份证号、姓名、性别和民族,而居民中的成年人又多两项数据:出生年月和职业,成年人中的党员又多一项数据:党员类别。现要求建立三个类,让成年人类继承居民类,而党员类继承成年人类,并要求在每个类中都提供有数据输入和输出的功能
时间: 2024-10-10 17:09:43 浏览: 24
为了满足这个需求,我们可以创建三个类:Resident, Adult, 和 PartyMember,使用继承层次来组织数据。以下是这三类的一个基础实现:
```python
class Resident:
def __init__(self, id_number, name, gender, ethnicity):
self.id_number = id_number
self.name = name
self.gender = gender
self.ethnicity = ethnicity
def display_data(self):
print(f"ID: {self.id_number}, Name: {self.name}, Gender: {self.gender}, Ethnicity: {self.ethnicity}")
def input_data(self, id_number=None, name=None, gender=None, ethnicity=None):
if id_number is not None:
self.id_number = id_number
if name is not None:
self.name = name
if gender is not None:
self.gender = gender
if ethnicity is not None:
self.ethnicity = ethnicity
class Adult(Resident):
def __init__(self, id_number, name, gender, ethnicity, birth_year_month):
super().__init__(id_number, name, gender, ethnicity)
self.birth_year_month = birth_year_month
def display_data(self):
super().display_data()
print(f"Birth Year and Month: {self.birth_year_month}")
def input_data(self, *args, **kwargs):
super().input_data(*args, **kwargs)
if 'birth_year_month' in kwargs:
self.birth_year_month = kwargs['birth_year_month']
class PartyMember(Adult):
def __init__(self, id_number, name, gender, ethnicity, birth_year_month, party_member_type):
super().__init__(id_number, name, gender, ethnicity, birth_year_month)
self.party_member_type = party_member_type
def display_data(self):
super().display_data()
print(f"Party Member Type: {self.party_member_type}")
def input_data(self, *args, **kwargs):
super().input_data(*args, **kwargs)
if 'party_member_type' in kwargs:
self.party_member_type = kwargs['party_member_type']
# 示例使用
resident = Resident('123456', '张三', '男', '汉')
resident.input_data(id_number='789012', name='李四', gender='女')
resident.display_data()
adult = PartyMember('123456', '王五', '男', '汉', '1985-06', '正式党员')
adult.input_data(birth_year_month='1987-12', party_member_type='预备党员')
adult.display_data()
```
这里,`Adult`类继承了`Resident`类,添加了出生年月的属性和数据输入方法;`PartyMember`类继承了`Adult`类,并增加了党员类型的属性和数据输入方法。
阅读全文