设计一个学生类和它的一个子类一一本科生类pta
时间: 2025-07-05 16:02:27 浏览: 6
### 设计 Python 中的学生类及继承自它的本科生类
为了实现这一目标,可以定义一个基础 `Student` 类来表示一般学生的属性和行为。对于特定类型的大学生,比如本科生,则可以通过继承该基类并扩展其功能。
#### 定义 Student 基础类
```python
class Student:
def __init__(self, name, student_id):
self.name = name
self.student_id = student_id
def get_info(self):
return f"Name: {self.name}, ID: {self.student_id}"
```
此部分代码创建了一个名为 `Student` 的基本类,它有两个私有变量用于存储姓名 (`name`) 和学号 (`student_id`) 。方法 `get_info()` 返回有关学生的信息字符串[^1]。
#### 创建 Undergraduate 子类
针对不同学校级别的参赛者分类需求,在这里进一步细化为具体的本科生类别:
```python
class Undergraduate(Student):
GROUPS = {
'A': "985、211",
'B': "其他本科院校",
'C': "高职、高专"
}
def __init__(self, name, student_id, school_type='C'):
super().__init__(name, student_id)
if school_type not in Undergraduate.GROUPS.keys():
raise ValueError(f"Invalid group type '{school_type}'. Valid options are A, B or C.")
self.school_type = school_type
def eligible_competition_groups(self):
groups = []
current_group_index = list(Undergraduate.GROUPS).index(self.school_type)
while True:
try:
key = list(Undergraduate.GROUPS)[current_group_index]
value = Undergraduate.GROUPS[key]
if key != 'C':
lang_options = ["C/C++", "Java"]
for lang in lang_options:
groups.append(f"{lang} 大学{value}")
elif key == 'C':
langs = ["C/C++", "Java", "Python"]
for l in langs:
groups.append(f"{l} 大学组")
current_group_index += 1
except IndexError:
break
return ", ".join(groups)
def register_for_competition(self, competition_group):
available_groups = set([g.strip() for g in self.eligible_competition_groups().split(',')])
if competition_group not in available_groups:
raise Exception(f"The selected competition group is invalid. Available choices include:\n\t{', '.join(available_groups)}")
print(f'Student "{self.name}" has successfully registered for the "{competition_group}".')
```
上述代码实现了如下特性:
- 继承了父类 `Student` 并增加了关于学校类型(`school_type`)的新参数。
- 提供了静态字典 `GROUPS` 来映射不同的分组标准到相应的描述。
- 方法 `eligible_competition_groups()` 计算当前实例能够参与的比赛项目列表。
- 函数 `register_for_competition()` 检查所选比赛是否属于允许范围内,并完成注册操作。
通过这种方式,可以根据具体的需求轻松调整或扩展此类结构以适应更复杂的应用场景。
阅读全文
相关推荐















