简体   繁体   English

具有相同名称但子类别不同的​​python例外

[英]python exceptions with same name but different subclassing

I am reading the python doc and it mentions that 我正在阅读python doc ,它提到

Two exception classes that are not related via subclassing are never equivalent, even if they have the same name. 通过子类不相关的两个异常类,即使它们具有相同的名称,也永远不会等效。

I'm not sure why it is possible to have two exception classes with the same name but different subclassing. 我不确定为什么可以有两个具有相同名称但不同子类化的异常类。 Shouldn't some kind of error/warning be generated in that case? 在这种情况下是否应该生成某种错误/警告?

Exceptions are just specific types of classes. 异常只是类的特定类型。 Class names are simply what they are defined as. 类名就是它们的定义。 Forbidding classes to have the same name would brake lots of coding schemes. 禁止具有相同名称的类会使很多编码方案停滞不前。 One such example actually works on exceptions: programs that need to be backwards compatible with python2.6 will often override subprocess.CalledProcessError to conform to the python2.7/3.X interface. 此类示例实际上适用于异常:需要与python2.6向后兼容的程序通常会覆盖subprocess.CalledProcessError以符合python2.7 / 3.X接口。

How can you have two exceptions of the same name but different subclassing? 如何拥有两个具有相同名称但不同子类的例外? You are for example free to do the following: 例如,您可以自由执行以下操作:

class ExceptoPatronum(KeyError):
    pass

KExcept = ExceptoPatronum

class ExceptoPatronum(OSError):
    pass

OExcept = ExceptoPatronum

The classes are named the same but neither equal nor instances of each other: 这些类的名称相同,但彼此不相等,也不相互实例:

print(KExcept.__name__)
print(OExcept.__name__)
print(KExcept == OExcept, KExcept is OExcept)

This is a (contrived) example that runs even with just one file. 这是一个(人为)示例,即使只有一个文件也可以运行。 However, imagine you have two separate modules which each define their own custom class with the same name, let's say ResourceUnavailable . 但是,假设您有两个单独的模块,每个模块都使用相同的名称定义自己的自定义类,比如说ResourceUnavailable

As long as they are separate, why should users be warned about such internals? 只要它们是分开的,为什么要警告用户这种内部结构? If another module relies on both, would you require it to replace them? 如果另一个模块依赖于这两个模块,您是否需要替换它们? It would be a nightmare to track such name collisions. 跟踪此类名称冲突将是一场噩梦。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM