如何重写AssertionError

时间:2019-06-11 16:22:56

标签: python testing error-handling

为响应能够覆盖断言错误的提示,有人建议我this

有人能帮助我如何重载AssertionError类,以便我可以执行AssertionError,它将调用我的自定义变量,例如图片中的一个吗?

2 个答案:

答案 0 :(得分:1)

您不能覆盖默认异常,但是可以创建一个具有相同名称的新异常类,并将其导入到您要使用它的文件中,如共享的图像所示。

例如:

custom_exception.py


class CustomAssertionError(Exception): 

    # Constructor or Initializer 
    def __init__(self, message): 
        # do your stuff here
        raise AssertionError(message)

usage.py

from custom_exception import AssertionError

def my_function():
    raise CustomAssertionError("some error message")

有关在python中创建自定义异常的更多详细信息,请遵循:Proper way to declare custom exceptions in modern Python?

答案 1 :(得分:0)

这是一种执行此操作的方法。这很丑陋,可能不太推荐,但它可以工作:(请注意,这在Python3中有效,Python2.7不同)

Example IPython code on how to override the builtin AssertionError class