【问题标题】:User-defind type with built-in type comparison [duplicate]具有内置类型比较的用户定义类型[重复]
【发布时间】:2016-05-20 07:18:04
【问题描述】:

我正在编写一个上下文管理器,允许捕获某种类型的异常。

class AssertRaises(object):
    def __init__(self, exc_type):
        self.exc_type = exc_type

    def __enter__(self):
        pass

    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type == self.exc_type:
            raise AssertionError
        return True

当内置异常引发但由于这种用法而失败时,此管理器工作正常:

class MyTypeError(TypeError):
    pass


try:
    with AssertRaises(TypeError):
        raise MyTypeError()
except Exception as e:
    print(type(e).__name__)

在此示例中,引发了用户定义的异常,但此异常等同于 TypeError,我希望上下文管理器将其作为 TypeError 处理。 我检查了 `isinstance(MyTypeError(), TypeError) == True' 并且想要

__exit__(...)

以相同的方式工作(考虑继承)。有什么解决办法吗?

【问题讨论】:

  • 平等不能测试子类,这就是 issubclass() 的用途。
  • 请注意,您不应该使用== 来测试类; issubclass(Class, Class) 也将返回 true(一个类被认为是它自己的一个子类)。并且不要在测试中使用== True;这已经暗示了。所以用if some_test:代替if some_test == True:,反之则为if not some_test:
  • 感谢您的帮助。我认为这是我一直在寻找的功能/

标签: python equality equivalence


【解决方案1】:

要么检查异常本身 (exc_val),就像你对 isinstance() 所做的那样,或者使用 issubclass()

def __exit__(self, exc_type, exc_val, exc_tb):
    if issubclass(exc_type, self.exc_type):
        raise AssertionError
    return True

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-07
    • 1970-01-01
    • 2019-01-23
    • 1970-01-01
    • 2016-07-26
    • 1970-01-01
    相关资源
    最近更新 更多