写一个基于python的宿舍管理系统代码
时间: 2024-06-09 22:12:09 浏览: 132
好的,以下是一个简单的基于Python的宿舍管理系统代码。它使用了Python的面向对象编程方法,包括类、对象、继承等。
```
class Student:
def __init__(self, name, age, gender, id_num):
self.name = name
self.age = age
self.gender = gender
self.id_num = id_num
class Room:
def __init__(self, number, capacity):
self.number = number
self.capacity = capacity
self.current_students = []
def add_student(self, student):
if len(self.current_students) < self.capacity:
self.current_students.append(student)
print(f"{student.name} has been added to room {self.number}.")
else:
print(f"The room {self.number} is full.")
class Dormitory:
def __init__(self, name, address):
self.name = name
self.address = address
self.rooms = []
def add_room(self, room):
self.rooms.append(room)
print(f"Room {room.number} has been added to the dormitory.")
def find_room(self, room_number):
for room in self.rooms:
if room.number == room_number:
return room
return None
def find_student(self, student_id):
for room in self.rooms:
for student in room.current_students:
if student.id_num == student_id:
return student
return None
def assign_student_to_room(self, student_id, room_number):
student = self.find_student(student_id)
room = self.find_room(room_number)
if student is None:
print(f"No student with ID {student_id} found.")
elif room is None:
print(f"No room with number {room_number} found.")
else:
room.add_student(student)
# Sample usage
jane = Student("Jane", 19, "F", "123456")
john = Student("John", 20, "M", "789012")
room1 = Room(101, 2)
dorm = Dormitory("ABC Dorm", "123 Main St.")
dorm.add_room(room1)
dorm.assign_student_to_room("123456", 101) # Jane added to room 101
dorm.assign_student_to_room("789012", 101) # John added to room 101
```
这个系统包括三个类:`Student`(学生)、`Room`(房间)和`Dormitory`(宿舍)。
`Student`类包括学生的基本信息,如姓名、年龄、性别和身份证号码。
`Room`类表示宿舍的房间,包括房间号码、容量和当前居住的学生列表。可以通过`add_student`方法将学生添加到房间中。
`Dormitory`类表示整个宿舍,包括名称、地址和房间列表。可以使用`add_room`方法添加房间,使用`find_room`方法查找指定房间,使用`find_student`方法查找指定学生,使用`assign_student_to_room`方法将学生分配到指定房间。
在代码的最后,我们创建了两个学生(Jane和John)、一个房间(101)和一个宿舍(ABC Dorm),并将两个学生分配给房间101。
阅读全文