adds和updates的运行结果问题
def adds(self, new_students):
for student in new_students:
try:
self.check_user_info(**student)
except Exception as e:
print(e, student.get('name'))
continue
self.__add(**student)
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('并不存在学号{}'.format(id_))
continue
try:
self.check_user_info(**student[id_])
except Exception as e:
print(e)
continue
self.students[id_] = student[id_]
print('更新完成')
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 'class_' not in kwargs:
raise NotArgError('缺少学生班级参数')
assert 'sex' in kwargs, '缺少学生性别参数'
name_value = kwargs['name']
age_value = kwargs['age']
class_value = kwargs['class_']
sex_value = kwargs['sex']
if not isinstance(name_value, str):
raise TypeError('name应该是字符串类型')
assert isinstance(age_value, int), 'age是整型'
if not isinstance(class_value, str):
raise TypeError('class_是字符串类型')
if not isinstance(sex_value, str):
raise TypeError('sex是字符串类型')
users = [
{'name': 'huahua', 'age': 2, 'class_': 'A'},
{'name': 'xiaoxin', 'age': 6, 'class_': 'C', 'sex': 'boy'},
{'name': 'heye', 'age': 2, 'sex': 'boy'}
]
student_info.adds(users)
updates = [
{1: {'name': 'dewei.Zhang', 'age': 33, 'class_': 'B', 'sex': 'boy'}},
{3: {'name': 'xiaoman', 'age': '30'}},
{9: {'name': 'xiaogao', 'age': 20, 'class_': 'B', 'sex': 'boy'}}
]
student_info.updates(updates)
结果:
参数必须是4个 huahua
参数必须是4个 heye
参数必须是4个
并不存在学号9
更新完成printe(e)返回的结果只有‘参数必须是4个’,不会返回后面这些信息了。我的理解是python执行到第一个异常的时候,就会停止,不再继续执行了(就想try也不会执行错误后面的指令)。那后面这些指令似乎就没有意义了。怎么可以修改呢?
check_user_info里,raise的语句是不是也可以用assert代替。只要是判断语句就可以用assert,不用raise?
11
收起
正在回答 回答被采纳积分+1
1回答
Python全能工程师
- 参与学习 人
- 提交作业 16421 份
- 解答问题 4469 个
全新版本覆盖5大热门就业方向:Web全栈、爬虫、数据分析、软件测试、人工智能,零基础进击Python全能型工程师,从大厂挑人到我挑大厂,诱人薪资在前方!
了解课程

恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星