宿舍管理系统代码
以下是一个简单的宿舍管理系统的 Python 代码示例。这只是一个非常基础的版本,你可能需要根据你的具体需求进行修改和扩展。
python复制代码class Dormitory: def __init__(self, name, capacity): self.name = name self.capacity = capacity self.students = [] def add_student(self, student): if len(self.students) < self.capacity: self.students.append(student) print(f"{student} has been added to {self.name}.") else: print(f"Sorry, {self.name} is full.") def remove_student(self, student): if student in self.students: self.students.remove(student) print(f"{student} has been removed from {self.name}.") else: print(f"{student} is not in {self.name}.") def list_students(self): print(f"Students in {self.name}: {self.students}") class Student: def __init__(self, name): self.name = name # 创建宿舍和学生 dorm1 = Dormitory("Dormitory A", 10) dorm2 = Dormitory("Dormitory B", 5) student1 = Student("Alice") student2 = Student("Bob") student3 = Student("Charlie") # 添加学生到宿舍 dorm1.add_student(student1) dorm1.add_student(student2) dorm2.add_student(student3) # 列出宿舍的学生 dorm1.list_students() dorm2.list_students() # 从宿舍移除学生 dorm1.remove_student(student1) dorm1.list_students()
这个代码定义了两个类:Dormitory 和 Student。Dormitory 类代表一个宿舍,具有名称、容量和居住的学生列表等属性。Student 类代表一个学生,只有一个名称属性。Dormitory 类有添加学生、移除学生和列出学生等方法。
这只是一个非常基础的示例,并没有处理很多实际可能出现的问题,例如学生重名、宿舍名称冲突、并发访问等问题。如果你需要在实际环境中使用这样的系统,你可能需要添加更多的错误处理、数据验证和并发控制等功能。此外,你可能还需要使用数据库来持久化存储宿舍和学生的信息,而不是像这个示例中那样只在内存中存储。