该章节我们来学习 异常的最后一个知识点 - 断言 ,断言是判断一个表达式,在表达式为 False 的时候触发异常。表达式我们可以对号入座,可以是条件语句中的声明,也可以是是 while 循环中的声明。
它们都是对一件事情进行 True 或者 False 的判断, 断言 也是如此,断言发现后面的表达式为 False 的时候 就会主动抛出异常。
在 Python 中 assert 就是断言的关键字,乍一听起来 似乎和 raise 关键字 的功能一样。其实 assert 断言的使用要比 raise 更加的简洁, rais 是生硬的抛出一个异常,而 assert 是先进行一个判断然后再根据结果选择是否要抛出这个异常。
比如我们对自己写的函数的结果进行一个判断,如果选择 raise 则需要自己手动写一个 if 按断的条件语句,然后再进行 raise ;而 assert 只要一行就可以轻松完成我们的任务
断言的功能与语法
断言的功能:简单来说,断言就是用于判断的一个表达式,当表达式的条件返回为 False 的时候触发异常。
断言的语法:示例如下
1
2
3
4
5
6
7
|
# 用法: assert exception, message # 参数: # exception:表达式,一般是判断相等;或者是判断是某种数据类型的 bool 判断的语句,再决定是否抛出异常 # message:指的是具体的错误信息,选填参数,可以不填写。(但是建议还是填写上) # 返回值:无返回值(虽然表达式有返回值,但 assert 没有;表达式为 Treu , assert 将不会触发任何异常) |
看一个简单的例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
assert 1 ! = 1 , '返回结果 \'False\' 1 等于 1' # >>> 执行结果如下: # >>> AssertionError: 返回结果 'False' 1 等于 1 # ******************************************** assert 1 > 2 , '返回结果 \'False\' ,抛出异常' # >>> 执行结果如下: # >>> AssertionError: 返回结果 'False' ,抛出异常 |
断言小实战
接下来我们根据我们之前面向对象章节的Python学习之面向函数转面向对象详解进行添加异常及异常的捕获然后再增加一个批量添加的功能。
源码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
|
""" @Author:Neo @Date:2020/1/16 @Filename:students_info.py @Software:Pycharm """ class NotArgError(Exception): def __init__( self , message): self .message = message class StudentInfo( object ): def __init__( self , students): self .students = students def get_by_id( self , student_id): return self .students.get(student_id) def get_all_students( 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, student.get( 'name' )) 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[ 'name' ])) 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)) 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[ 'sex' ] 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: # [{name, sex, age, class_number}, {}] 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' ] # type(name_value) age_value = kwargs[ 'age' ] sex_value = kwargs[ 'sex' ] class_number_value = kwargs[ 'class_number' ] # isinstace(对比的数据, 目标类型) isinstance(1, str) 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' : 'Neo' , 'age' : 18 , 'class_number' : 'A' , 'sex' : 'boy' }, 2 : { 'name' : 'Jack' , 'age' : 16 , 'class_number' : 'B' , 'sex' : 'boy' }, 3 : { 'name' : 'Lily' , 'age' : 18 , 'class_number' : 'A' , 'sex' : 'girl' }, 4 : { 'name' : 'Adem' , 'age' : 18 , 'class_number' : 'C' , 'sex' : 'boy' }, 5 : { 'name' : 'HanMeiMei' , 'age' : 18 , 'class_number' : 'B' , 'sex' : 'girl' } } if __name__ = = '__main__' : student_info = StudentInfo(students) user = student_info.get_by_id( 1 ) student_info.add(name = 'Marry' , age = 16 , class_number = 'A' , sex = 'girl' ) users = [ { 'name' : 'Atom' , 'age' : 17 , 'class_number' : 'B' , 'sex' : 'boy' }, { 'name' : 'Lucy' , 'age' : 18 , 'class_number' : 'C' , 'sex' : 'girl' } ] student_info.adds(users) student_info.get_all_students() print ( '------------------------------------------------------' ) # >>> 执行结果如下: # >>> 学号:1, 姓名:Neo, 年龄:18, 性别:boy, 班级:A # >>> 学号:2, 姓名:Jack, 年龄:16, 性别:boy, 班级:B # >>> 学号:3, 姓名:Lily, 年龄:18, 性别:girl, 班级:A # >>> 学号:4, 姓名:Adem, 年龄:18, 性别:boy, 班级:C # >>> 学号:5, 姓名:HanMeiMei, 年龄:18, 性别:girl, 班级:B # >>> 学号:6, 姓名:Marry, 年龄:16, 性别:girl, 班级:A # >>> 学号:7, 姓名:Atom, 年龄:17, 性别:boy, 班级:B # >>> 学号:8, 姓名:Lucy, 年龄:18, 性别:girl, 班级:C # >>> ------------------------------------------------------ student_info.deletes([ 7 , 8 ]) student_info.get_all_students() print ( '------------------------------------------------------' ) # >>> 执行结果如下: # >>> ------------------------------------------------------ # >>> 学号7 学生Atom 已被移除 # >>> 学号8 学生Lucy 已被移除 # >>> 学号:1, 姓名:Neo, 年龄:18, 性别:boy, 班级:A # >>> 学号:2, 姓名:Jack, 年龄:16, 性别:boy, 班级:B # >>> 学号:3, 姓名:Lily, 年龄:18, 性别:girl, 班级:A # >>> 学号:4, 姓名:Adem, 年龄:18, 性别:boy, 班级:C # >>> 学号:5, 姓名:HanMeiMei, 年龄:18, 性别:girl, 班级:B # >>> 学号:6, 姓名:Marry, 年龄:16, 性别:girl, 班级:A # >>> ------------------------------------------------------ student_info.updates([ { 1 : { 'name' : 'Jone' , 'age' : 18 , 'class_number' : 'A' , 'sex' : 'boy' }}, { 2 : { 'name' : 'Nike' , 'age' : 18 , 'class_number' : 'A' , 'sex' : 'boy' }} ]) student_info.get_all_students() print ( '------------------------------------------------------' ) # >>> 执行结果如下: # >>> ------------------------------------------------------ # >>> 所有用户信息更新完成 # >>> 学号:1, 姓名:Jone, 年龄:18, 性别:boy, 班级:A # >>> 学号:2, 姓名:Nike, 年龄:18, 性别:boy, 班级:A # >>> 学号:3, 姓名:Lily, 年龄:18, 性别:girl, 班级:A # >>> 学号:4, 姓名:Adem, 年龄:18, 性别:boy, 班级:C # >>> 学号:5, 姓名:HanMeiMei, 年龄:18, 性别:girl, 班级:B # >>> 学号:6, 姓名:Marry, 年龄:16, 性别:girl, 班级:A # >>> ------------------------------------------------------ result = student_info.search_users(name = 'd' ) print (result) print ( '------------------------------------------------------' ) # >>> 执行结果如下: # >>> [{'name': 'Adem', 'age': 18, 'class_number': 'C', 'sex': 'boy'}] result = student_info.search_users(name = '小' ) print (result) print ( '------------------------------------------------------' ) # >>> 执行结果如下: # >>> ------------------------------------------------------ # >>> [] # >>> ------------------------------------------------------ result = student_info.search_users(name = '') print (result) result = student_info.search_users(name = '小' ) print (result) print ( '------------------------------------------------------' ) # >>> 执行结果如下: # >>> ------------------------------------------------------ # >>> [{'name': 'Jone', 'age': 18, 'class_number': 'A', 'sex': 'boy'}, {'name': 'Nike', 'age': 18, 'class_number': 'A', 'sex': 'boy'}, {'name': 'Lily', 'age': 18, 'class_number': 'A', 'sex': 'girl'}, {'name': 'Adem', 'age': 18, 'class_number': 'C', 'sex': 'boy'}, {'name': 'HanMeiMei', 'age': 18, 'class_number': 'B', 'sex': 'girl'}, {'name': 'Marry', 'age': 16, 'class_number': 'A', 'sex': 'girl'}] # >>> [] result = student_info.search_users(name = '') print (result) |
以上就是Python学习之异常断言详解的详细内容,更多关于Python异常断言的资料请关注服务器之家其它相关文章!
原文链接:https://blog.csdn.net/weixin_42250835/article/details/123535439