assert.md 2.4 KB
Newer Older
F
feilong 已提交
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
# Python 断言

所谓断言,就是证明,使用 assert 对输入函数输入参数和函数返回结果分别做前校验和后校验

```python
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
```