无名 发表于 2022-5-8 18:37:31

【HC】python装B语法十

这是最后一期
这里小亚,
——————
巧用断言assert
所谓断言,就是声明表达式的布尔值必须为真的判定,否则将触发 AssertionError 异常。严格来讲,assert是调试手段,不宜使用在生产环境中,但这不影响我们用断言来实现一些特定功能,比如,输入参数的格式、类型验证等。
>>> def i_want_to_sleep(delay):
        assert(isinstance(delay, (int,float))), '函数参数必须为整数或浮点数'
        print('开始睡觉')
        time.sleep(delay)
        print('睡醒了')

       
>>> i_want_to_sleep(1.1)
开始睡觉
睡醒了
>>> i_want_to_sleep(2)
开始睡觉
睡醒了
>>> i_want_to_sleep('2')
Traceback (most recent call last):
File "", line 1, in
    i_want_to_sleep('2')
File "", line 2, in i_want_to_sleep
    assert(isinstance(delay, (int,float))), '函数参数必须为整数或浮点数'
AssertionError: 函数参数必须为整数或浮点数
http://cdn.u1.huluxia.com/g3/M01/49/CD/wKgBOV3Sbc6AKJpeAAFAIevZ-vc788.jpg
页: [1]
查看完整版本: 【HC】python装B语法十