Advertisement
adolphuZ

Untitled

Jun 5th, 2024
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.36 KB | None | 0 0
  1. import json
  2.  
  3. class SaveError(Exception):
  4.     def __init__(self, message):
  5.         super().__init__(f"SaveError: {message}")
  6.  
  7. class LoadError(Exception):
  8.     def __init__(self, message):
  9.         super().__init__(f"LoadError: {message}")
  10.  
  11. class Osoba:
  12.     def __init__(self, name, last_name, age):
  13.         self.name = name
  14.         self.last_name = last_name
  15.         self.age = age
  16.  
  17.     def get_name(self):
  18.         return self.name
  19.  
  20.     def get_last_name(self):
  21.         return self.last_name
  22.  
  23.     def get_age(self):
  24.         return self.age
  25.  
  26.     def to_dict(self):
  27.         return {
  28.             'name': self.name,
  29.             'last_name': self.last_name,
  30.             'age': self.age
  31.         }
  32.  
  33. class Note:
  34.     def __init__(self, grades):
  35.         self.grades = grades
  36.  
  37.     def get_grades(self):
  38.         return self.grades
  39.  
  40.     def get_grade(self, subject):
  41.         return self.grades.get(subject, None)
  42.  
  43.     def to_dict(self):
  44.         return self.grades
  45.  
  46. class Student(Osoba):
  47.     def __init__(self, name, last_name, age, index_nr, grades):
  48.         super().__init__(name, last_name, age)
  49.         self.index_nr = index_nr
  50.         self.notes = Note(grades)
  51.  
  52.     def get_index_nr(self):
  53.         return self.index_nr
  54.  
  55.     def get_notes(self):
  56.         return self.notes.get_grades()
  57.  
  58.     def to_dict(self):
  59.         data = super().to_dict()
  60.         data.update({
  61.             'index_nr': self.index_nr,
  62.             'grades': self.notes.to_dict()
  63.         })
  64.         return data
  65.  
  66. class Group:
  67.     def __init__(self):
  68.         self.students = []
  69.  
  70.     def add_student(self, student):
  71.         self.students.append(student)
  72.  
  73.     def get_students(self):
  74.         return self.students
  75.  
  76.     def display_students(self):
  77.         for student in self.students:
  78.             print(f"Student: {student.get_name()} {student.get_last_name()}, Age: {student.get_age()}, Index: {student.get_index_nr()}")
  79.             print(f"Grades: {student.get_notes()}")
  80.  
  81.     def save_to_file(self, filename):
  82.         try:
  83.             with open(filename, 'w') as file:
  84.                 json.dump([student.to_dict() for student in self.students], file, indent=4)
  85.             print(f"Data successfully saved to {filename}")
  86.         except IOError as e:
  87.             raise SaveError(f"An error occurred while writing to the file: {e}")
  88.  
  89.     def load_from_file(self, filename):
  90.         try:
  91.             with open(filename, 'r') as file:
  92.                 data = json.load(file)
  93.                 self.students = []
  94.                 for student_data in data:
  95.                     student = Student(
  96.                         student_data['name'],
  97.                         student_data['last_name'],
  98.                         student_data['age'],
  99.                         student_data['index_nr'],
  100.                         student_data['grades']
  101.                     )
  102.                     self.add_student(student)
  103.             print(f"Data successfully loaded from {filename}")
  104.         except IOError as e:
  105.             raise LoadError(f"An error occurred while reading the file: {e}")
  106.         except json.JSONDecodeError as e:
  107.             raise LoadError(f"An error occurred while decoding JSON data: {e}")
  108.  
  109. # Przykładowa inicjalizacja studentów
  110. grades_student1 = {
  111.     "Mathematics": 5,
  112.     "Physics": 4,
  113.     "Chemistry": 3
  114. }
  115.  
  116. grades_student2 = {
  117.     "Mathematics": 4,
  118.     "Physics": 5,
  119.     "Chemistry": 4
  120. }
  121.  
  122. student1 = Student("Anna", "Nowak", 22, "2021001", grades_student1)
  123. student2 = Student("Piotr", "Kowalski", 23, "2021002", grades_student2)
  124.  
  125. # Przykładowa inicjalizacja grupy z dowolnymi studentami
  126. group = Group()
  127. group.add_student(student1)
  128. group.add_student(student2)
  129.  
  130. # Zapis grupy studentów do pliku
  131. try:
  132.     group.save_to_file("students_group.json")
  133. except SaveError as e:
  134.     print(e)
  135.  
  136. # Wyświetlenie studentów w grupie przed odczytem z pliku
  137. print("\nGroup before loading from file:")
  138. group.display_students()
  139.  
  140. # Symulacja błędu odczytu - zmiana nazwy pliku na nieistniejący
  141. print("\nSimulating file read error:")
  142. try:
  143.     group.load_from_file("nonexistent_file.json")
  144. except LoadError as e:
  145.     print(e)
  146.  
  147. # Odczyt grupy studentów z pliku
  148. try:
  149.     group.load_from_file("students_group.json")
  150. except LoadError as e:
  151.     print(e)
  152.  
  153. # Wyświetlenie studentów w grupie po odczycie z pliku
  154. print("\nGroup after loading from file:")
  155. group.display_students()
  156.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement