# Python 断言 所谓断言,就是证明,使用 assert 对输入函数输入参数和函数返回结果分别做前校验和后校验 ```python # -*- coding: UTF-8 -*- def check_param(key_value_map, key): '''参数校验,断言就是对输入参数的一个证明,这些参数必须符合这些要求 key_value_map: 非空字典 key:非空字符串 ''' # TODO(You): 请在此实现校验代码 def get(key_value_map, key): check_param(key_value_map, key) return key_value_map.get(key) def set(key_value_map, key, value): check_param(key_value_map, key) key_value_map[key] = value if __name__ == '__main__': key_value_map = {} set(key_value_map, "test", {}) value = get(key_value_map, "test") print("后校验,返回值必须符合预期") assert type(value) == type({}) assert value == {} ``` 请选出下列对函数 check_param **实现错误**的选项。 ## template ```python def check_param(key_value_map, key): '''参数校验,断言就是对输入参数的一个证明,这些参数必须符合这些要求''' assert key_value_map is not None assert type(key_value_map) == type({}) assert key is not None assert type(key) == type("") def get(key_value_map, key): check_param(key_value_map, key) return key_value_map.get(key) def set(key_value_map, key, value): check_param(key_value_map, key) key_value_map[key] = value if __name__ == '__main__': key_value_map = {} set(key_value_map, "test", {}) value = get(key_value_map, "test") print("后校验,返回值必须符合预期") assert type(value) == type({}) assert value == {} ``` ## 答案 ```python def check_param(key_value_map, key): assert key_value_map assert type(key_value_map) == dict assert key assert type(key) == str ``` ## 选项 ### A ```python def check_param(key_value_map, key): assert key_value_map is not None assert type(key_value_map) == type({}) assert key is not None assert type(key) == type("") ``` ### B ```python def check_param(key_value_map, key): assert key_value_map is not None and type(key_value_map) == type({}) assert key is not None and type(key) == type("") ``` ### C ```python def check_param(key_value_map, key): assert key_value_map is not None assert type(key_value_map) == dict assert key is not None assert type(key) == str ```