The question is, when I want to add a new student, the code doesn't save the student's data to a .db file? The .db file was created but empty.. a.save() doesn't work, you have to save with id. Here is the full code:
import shelve
class Student():
path = 'Students'
def __init__(self, name, age, mark, level, id=None):
self.name = name
self.age = age
self.mark = mark
self.level = level
self.id = id
@property
def name(self):
return self.__name
@name.setter
def name(self, name):
if isinstance(name,str) and name.isalpha():
self.__name = name
else:
self.__name = "Error"
@property
def age(self):
return self.__age
@age.setter
def age(self, age):
if isinstance(age, int) and age > 0 and age < 120:
self.__age = age
else:
self.__age = 0
@property
def mark(self):
return self.__mark
@mark.setter
def mark(self, mark):
if isinstance(mark, int) and mark > 0 and mark < 10:
self.__mark = mark
else:
self.__mark = 0
@property
def level(self):
return self.__level
@level.setter
def level(self, level):
if isinstance(level, int) and level > 0 and level < 5:
self.__level = level
else:
self.__level = 0
def save(self):
with shelve.open(Student.path) as students:
keys = list(students.keys())
if len(keys) > 0:
id = int(keys[-1]) + 1
students[str(id)] = self
else:
id = 1
self.id = str(id)
def update(self):
with shelve.open(Student.path) as students:
students[self.id] = self
def objects():
objs = []
with shelve.open(Student.path) as students:
for item in students.values():
objs.append(item)
return objs
def get_by_id(id):
with shelve.open(Student.path) as students:
return students[id]
def __str__(self) -> str:
return f'{self.id} {self.name} {self.age} {self.mark} {self.level}'
def printList():
for student in Student.objects():
print(student)
def Filtr():
print(" Filter ")
print("1.Name")
print("2.Level")
print("3.Age")
print("4.Mark")
n = int(input("Answer: "))
lpeopl = []
if n > 0 and n <= 4:
if n == 1:
n = input("Enter the first letter of the name you want to find in the list: ")
for item in Student.objects():
if item.name.startswith(n):
lpeopl.append(item)
if len(lpeopl) != 0:
for item in lpeopl:
print(item)
elif n == 2:
n = input("Enter a level: ")
for item in Student.objects():
if item.level==n:
print(item)
elif n == 3:
n=int(input("Enter an age:"))
for item in Student.objects():
if item.age==n:
print(item)
elif n == 4:
n=int(input("Enter a mark:"))
for item in Student.objects():
if item.mark==n:
print(item)
else:
print("Select 1 of menu")
def menu():
print("1. Display a list of students")
print("2. Add a new student")
print("3. Filter student")
javob = int(input("Answer: "))
if javob == 1:
printList()
elif javob == 2:
ism = input("Name: ")
age = int(input("Age: "))
mark = int(input("Mark: "))
level = int(input("Level: "))
a = Student(ism, age, mark, level)
a.save()
printList()
elif javob == 3:
Filtr()
menu()