cnq 发表于 2018-8-4 09:10:14

python中assert断言的用法

  >>> assert 1 == 0
  Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  AssertionError
  >>> assert 1 == 1
  assert断言是一句必须等价于布尔真的判定!
  1 不等于 0 就会有AssertionError异常
  1 等于 0 就没有异常
  如果断言成功(如果为真)那么不执行任何操作!
  如果断言不成功,那么会触发AssertionError
  -------------------------------------------------------------
  我们还可使用异常参数:
  用法:assert expression 【,argument】(异常参数可有可无)
  >>> assert 1 == 0,'one does not equal zero'
  Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  AssertionError: one does not equal zero
  -------------------------------------------------------------
  在try-except语句中使用assert:
  >>> try:
  ...   assert 1 == 0,'one does not equal zero'
  ... except AssertionError,args:
  ...   print '%s:%s' % (args.__class__.__name__,args)
  ...
  AssertionError:one does not equal zero            #输出
页: [1]
查看完整版本: python中assert断言的用法