断言-assert

一、简介

  在开发一个程序时候,与其让它运行时崩溃,不如在它出现错误条件时就崩溃(返回错误AssertionError)。这时候断言assert 就显得非常有用。

assert expression

    它的等价语句为: 

if not expression:
    raise AssertionError

 

二、使用时机

  那么我们什么时候应该使用断言呢?如果没有特别的目的,断言应该用于如下情况:

  • 防御性编程
  • 运行时对程序逻辑的检测
  • 合约性检查
  • 程序中的常量
  • 检查文档

三、事例

  断言正确

class Person(object):

    def __init__(self, name):
        self.name = name

    def hobby(self, interesting):
        print('{}\'s hobby is {}'.format(self.name, interesting))

p = Person('bigberg')

assert hasattr(p, 'hobby')
p.hobby('football')

# 输出

bigberg's hobby is football

  

  断言出错 

class Person(object):

    def __init__(self, name):
        self.name = name

    def hobby(self, interesting):
        print('{}\'s hobby is {}'.format(self.name, interesting))

p = Person('bigberg')

assert hasattr(p, 'sport')
p.sport('football')   # 不会被执行


# 输出

Traceback (most recent call last):
  File "G:/python/untitled/study8/断言.py", line 14, in <module>
    assert hasattr(p, 'sport')
AssertionError

  

posted @ 2017-10-28 15:27  Bigberg  阅读(922)  评论(0编辑  收藏  举报