简体   繁体   English

什么是 Java 的 UnsupportedOperationException 的 Python 等价物?

[英]What is the Python equivalent of Java's UnsupportedOperationException?

I'm looking at Python's built-in exceptions and wondering what the closest equivalent of Java's UnsupportedOperationException is.我正在查看 Python 的内置异常,并想知道与 Java 的UnsupportedOperationException最接近的等价物是什么。 NotImplementedError is close but seems to suggest something slightly different. NotImplementedError很接近,但似乎暗示了一些略有不同的东西。 Should I be using RuntimeError or implementing my own Exception ?我应该使用RuntimeError还是实现我自己的Exception

The closest equivalent is to simply not implement the unsupported method. 最接近的等价物是不执行不受支持的方法。 The resulting exception if you try to use the nonexistent method is an AttributeError . 如果尝试使用不存在的方法,则产生的异常是AttributeError

I don't know Java, but looking at what you linked to (and a few examples online), I'd say there is no single equivalent. 我不知道Java,但看看你链接到什么(以及一些在线例子),我会说没有单一的等价物。 That is quite a broad description for an exception type. 这是异常类型的相当广泛的描述。

If the operation isn't supported because the types of the operands are wrong, you'd use TypeError. 如果由于操作数的类型错误而不支持该操作,则使用TypeError。 If it isn't supported because the values are incompatible somehow, you'd use ValueError. 如果由于值不兼容而不支持它,则使用ValueError。 Or, as user2357112 notes, you would just do nothing and get an AttributeError when you tried to access a nonexistent method. 或者,如user2357112所述,当您尝试访问不存在的方法时,您将不会执行任何操作并获取AttributeError。

根据 Python 文档页面, NotImplementedError似乎是一个合适的选择。

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

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