Files
ailearning/docs/da/026.md
2020-10-19 21:08:55 +08:00

52 lines
952 B
Markdown
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 警告
出现了一些需要让用户知道的问题,但又不想停止程序,这时候我们可以使用警告:
首先导入警告模块:
In [1]:
```py
import warnings
```
在需要的地方,我们使用 `warnings` 中的 `warn` 函数:
```py
warn(msg, WarningType = UserWarning)
```
In [2]:
```py
def month_warning(m):
if not 1<= m <= 12:
msg = "month (%d) is not between 1 and 12" % m
warnings.warn(msg, RuntimeWarning)
month_warning(13)
```
```py
c:\Anaconda\lib\site-packages\IPython\kernel\__main__.py:4: RuntimeWarning: month (13) is not between 1 and 12
```
有时候我们想要忽略特定类型的警告,可以使用 `warnings``filterwarnings` 函数:
```py
filterwarnings(action, category)
```
`action` 设置为 `'ignore'` 便可以忽略特定类型的警告:
In [3]:
```py
warnings.filterwarnings(action = 'ignore', category = RuntimeWarning)
month_warning(13)
```