断言的功能--assert
- 用于判断一个表达式,在表达到条件为false的时候触发异常
断言的用法--assert
- 用法:
assert expression, message
- 参数:
-
expression
: 表达式,一般是判断相等,或者判断是某种数据类型的bool判断的语句 -
message
: 具体的错误信息,非必填
-
-
返回值:无
isinstance函数
- 用于判断对比数据是否为目标数据类型
- isinstance(对比的数据,目标数据类型)
- 返回bool类型
对学生信息库进行异常调整
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2021/8/14 13:32
# @Author : InsaneLoafer
# @File : test.py
"""
学生信息库
"""
class NotArgError(Exception):
def __init__(self, message):
self.message = message
class StudentsInfo(object):
def __init__(self, students):
self.students = students
def get_by_id(self, student_id):
return self.students.get(student_id)
def get_all(self):
for id_, value in self.students.items():
print('学号{},姓名{},年龄{},性别{},班级{}'.format(
id_, value['name'], value['age'], value['sex'], value['class_number']
))
return self.students
def add(self, **student):
try:
self.check_user_info(**student)
except Exception as e:
raise e
self.__add(**student)
# 实现批量添加
def adds(self, new_students):
for student in new_students:
try:
self.check_user_info(**student)
except Exception as e:
print(e)
continue
self.__add(**student)
def __add(self, **student):
new_id = max(self.students) + 1
self.students[new_id] = student
def delete(self, student_id):
if student_id not in self.students:
print('{}并不存在'.format(student_id))
else:
user_info = self.students.pop(student_id)
print('学号是{},{}同学的信息已被删除'.format(
student_id, user_info
))
def deletes(self, ids):
for id_ in ids:
if id_ not in self.students:
print(f'{id_} 不存在学生库中')
continue
student_info = self.students.pop(id_)
print(f'学号{id_} 学生 {student_info["name"]} 已被移除')
def update(self, student_id, **kwargs):
if student_id not in self.students:
print('并不存在这个学号{}'.format(student_id))
return
try:
self.check_user_info(**kwargs)
except Exception as e:
raise e
self.students[student_id] = kwargs
print('同学信息更新完毕')
def updates(self, update_students):
for student in update_students:
try:
id_ = list(student.keys())[0]
except IndexError as e:
print(e)
continue
if id_ not in self.students:
print(f'学号{id_} 不存在')
continue
user_info = student[id_]
try:
self.check_user_info(**user_info)
except Exception as e:
print(e)
continue
self.students[id_] = user_info
print('所有用户信息更新完成')
def search_users(self, **kwargs):
assert len(kwargs) == 1, '参数数量传递错误'
values = list(self.students.values())
key = None
value = None
result = []
if 'name' in kwargs:
key = 'name'
value = kwargs[key]
elif 'sex' in kwargs:
key = 'sex'
value = kwargs[key]
elif 'class_number' in kwargs:
key = 'class_number'
value = kwargs[key]
elif 'age' in kwargs:
key = 'age'
value = kwargs[key]
else:
raise NotArgError('没有发现搜索的关键字')
for user in values:
if value in user[key]: # 实现模糊查找
result.append(user)
return result
def check_user_info(self, **kwargs):
assert len(kwargs) == 4, '参数必须是4个'
if 'name' not in kwargs:
raise NotArgError('没有发现学生姓名')
if 'age' not in kwargs:
raise NotArgError('缺少学生年龄')
if 'sex' not in kwargs:
raise NotArgError('缺少学生性别')
if 'class_number' not in kwargs:
raise NotArgError('缺少学生班级')
name_value = kwargs['name']
age_value = kwargs['age']
sex_value = kwargs['sex']
class_number_value = kwargs['class_number']
if not isinstance(name_value, str):
raise TypeError('name 应该是字符串类型')
if not isinstance(age_value, int):
raise TypeError('age 应该是整型')
if not isinstance(sex_value, str):
raise TypeError('sex 应该是字符串类型')
if not isinstance(class_number_value, str):
raise TypeError('class_number 应该是字符串类型')
students = {
1: {
'name': 'insane',
'age': 23,
'class_number': 'A',
'sex': 'boy'
},
2: {
'name': 'loafer',
'age': 24,
'class_number': 'B',
'sex': 'boy'
},
3: {
'name': 'Nancy',
'age': 25,
'class_number': 'A',
'sex': 'girl'
},
4: {
'name': 'xiaogao',
'age': 26,
'class_number': 'C',
'sex': 'boy'
},
5: {
'name': 'xiaoyun',
'age': 18,
'class_number': 'B',
'sex': 'girl'
}
}
if __name__ == '__main__':
student_info = StudentsInfo(students=students)
user = student_info.get_by_id(2)
print(user)
student_info.add(name='123', age=23, class_number='B', sex='boy')
print(student_info.students)
users = [
{'name': 'xiaohua', 'age': 23, 'class_number': 'C', 'sex': 'boy'},
{'name': 'xiaoming', 'age': 23, 'class_number': 'B', 'sex': 'boy'},
]
student_info.adds(users)
student_info.get_all()
print('-----------')
student_info.deletes([7, 8])
student_info.get_all()
print('-----------')
student_info.updates([
{1: {'name': 'insaneloafer', 'age': 18, 'class_number': 'A', 'sex': 'boy'}},
{2: {'name': 'opadf', 'age': 18, 'class_number': 'B', 'sex': 'boy'}}
])
student_info.get_all()
print('--------')
result = student_info.search_users(name='xiao') # 模糊查询姓名含油xiao的学生信息
print(result)
print('--------')
result = student_info.search_users(name='')
print(result) # 打印所有信息
{'name': 'loafer', 'age': 24, 'class_number': 'B', 'sex': 'boy'}
{1: {'name': 'insane', 'age': 23, 'class_number': 'A', 'sex': 'boy'}, 2: {'name': 'loafer', 'age': 24, 'class_number': 'B', 'sex': 'boy'}, 3: {'name': 'Nancy', 'age': 25, 'class_number': 'A', 'sex': 'girl'}, 4: {'name': 'xiaogao', 'age': 26, 'class_number': 'C', 'sex': 'boy'}, 5: {'name': 'xiaoyun', 'age': 18, 'class_number': 'B', 'sex': 'girl'}, 6: {'name': '123', 'age': 23, 'class_number': 'B', 'sex': 'boy'}}
学号1,姓名insane,年龄23,性别boy,班级A
学号2,姓名loafer,年龄24,性别boy,班级B
学号3,姓名Nancy,年龄25,性别girl,班级A
学号4,姓名xiaogao,年龄26,性别boy,班级C
学号5,姓名xiaoyun,年龄18,性别girl,班级B
学号6,姓名123,年龄23,性别boy,班级B
学号7,姓名xiaohua,年龄23,性别boy,班级C
学号8,姓名xiaoming,年龄23,性别boy,班级B
-----------
学号7 学生 xiaohua 已被移除
学号8 学生 xiaoming 已被移除
学号1,姓名insane,年龄23,性别boy,班级A
学号2,姓名loafer,年龄24,性别boy,班级B
学号3,姓名Nancy,年龄25,性别girl,班级A
学号4,姓名xiaogao,年龄26,性别boy,班级C
学号5,姓名xiaoyun,年龄18,性别girl,班级B
学号6,姓名123,年龄23,性别boy,班级B
-----------
所有用户信息更新完成
学号1,姓名insaneloafer,年龄18,性别boy,班级A
学号2,姓名opadf,年龄18,性别boy,班级B
学号3,姓名Nancy,年龄25,性别girl,班级A
学号4,姓名xiaogao,年龄26,性别boy,班级C
学号5,姓名xiaoyun,年龄18,性别girl,班级B
学号6,姓名123,年龄23,性别boy,班级B
--------
[{'name': 'xiaogao', 'age': 26, 'class_number': 'C', 'sex': 'boy'}, {'name': 'xiaoyun', 'age': 18, 'class_number': 'B', 'sex': 'girl'}]
--------
[{'name': 'insaneloafer', 'age': 18, 'class_number': 'A', 'sex': 'boy'}, {'name': 'opadf', 'age': 18, 'class_number': 'B', 'sex': 'boy'}, {'name': 'Nancy', 'age': 25, 'class_number': 'A', 'sex': 'girl'}, {'name': 'xiaogao', 'age': 26, 'class_number': 'C', 'sex': 'boy'}, {'name': 'xiaoyun', 'age': 18, 'class_number': 'B', 'sex': 'girl'}, {'name': '123', 'age': 23, 'class_number': 'B', 'sex': 'boy'}]
Process finished with exit code 0