班级查找学生信息(支持模糊查询)代码
时间: 2023-12-20 12:13:39 浏览: 32
以下是一个简单的班级查找学生信息的 Python 代码,支持模糊查询:
```python
class Student:
def __init__(self, name, age, gender, grade):
self.name = name
self.age = age
self.gender = gender
self.grade = grade
class Class:
def __init__(self, students):
self.students = students
def search(self, keyword):
result = []
for student in self.students:
if keyword in student.name:
result.append(student)
return result
# 使用示例
students = [
Student("张三", 18, "男", 80),
Student("李四", 19, "女", 90),
Student("王五", 20, "男", 85)
]
my_class = Class(students)
result = my_class.search("张")
for student in result:
print(student.name, student.age, student.gender, student.grade)
```
在这个例子中,我们先定义了一个 `Student` 类来表示学生,然后定义了一个 `Class` 类来表示班级,其中包含一个 `students` 属性来存储班级中的学生。`Class` 类还定义了一个 `search` 方法,用来搜索学生信息。该方法接受一个关键字作为参数,然后遍历班级中的学生,如果学生的名字包含该关键字,则将该学生加入到结果列表中。最后,该方法返回结果列表。
在使用示例中,我们创建了一个班级对象 `my_class`,然后调用了 `search` 方法来搜索名字中包含关键字“张”的学生信息。最终,我们输出了查询结果中每个学生的姓名、年龄、性别和成绩。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)