python:实现学生通讯录
时间: 2023-07-12 11:59:01 浏览: 101
python tkinter 实现学生通讯录
好的,我可以为您提供一个基本的Python学生通讯录实现,您可以根据自己的需求进行修改和扩展。
```python
class Student:
def __init__(self, name, age, phone_number):
self.name = name
self.age = age
self.phone_number = phone_number
def __str__(self):
return f"{self.name} ({self.age}), {self.phone_number}"
class StudentDirectory:
def __init__(self):
self.students = []
def add_student(self, student):
self.students.append(student)
def remove_student(self, student):
self.students.remove(student)
def search_by_name(self, name):
matches = []
for student in self.students:
if student.name.lower() == name.lower():
matches.append(student)
return matches
def search_by_age(self, age):
matches = []
for student in self.students:
if student.age == age:
matches.append(student)
return matches
def search_by_phone_number(self, phone_number):
matches = []
for student in self.students:
if student.phone_number == phone_number:
matches.append(student)
return matches
def print_directory(self):
for student in self.students:
print(student)
# Example usage:
directory = StudentDirectory()
directory.add_student(Student("Alice", 18, "123-456-7890"))
directory.add_student(Student("Bob", 19, "234-567-8901"))
print("All students:")
directory.print_directory()
print("\nStudents named Alice:")
for student in directory.search_by_name("Alice"):
print(student)
print("\nStudents aged 18:")
for student in directory.search_by_age(18):
print(student)
print("\nStudents with phone number 234-567-8901:")
for student in directory.search_by_phone_number("234-567-8901"):
print(student)
```
在上面的代码中,我们定义了两个类:`Student` 和 `StudentDirectory`。每个 `Student` 对象代表一个学生,包含姓名、年龄和电话号码等信息。`StudentDirectory` 对象代表整个学生通讯录,提供添加、删除和搜索学生等操作。
您可以根据自己的需求扩展这个基本实现。例如,您可以添加更多的学生信息字段,或者增加其他的操作(例如按照成绩排序、导出到文件等)。
阅读全文