gpt4 book ai didi

使用内置异常的 Python

转载 作者:太空狗 更新时间:2023-10-29 23:59:20 24 4
gpt4 key购买 nike

我相信你很清楚,python 和大多数编程语言一样,都带有 built-in exceptions。 .我已经浏览了列表,无法推断出哪个是合适的。当然,我可以创建自己的异常,但这是一个相当标准的错误,应该被排除。

这是基于实例关系的错误。类的实例仅与某些其他实例相关。可以根据不同的连接进行计算。如果尝试在不相关的实例上进行计算,则此错误将引发

例子

class Foo:
def __init__(self,related=None):
'''related is a list of Foo instances'''
if related is not None:
self.related = related
else:
self.related = []
def compute(self,instance):
if instance in self.related:
#execute code
else:
raise SomeError("You cannot make a computation with an unrelated instance")

我的想法

老实说,ValueError 似乎最有意义,因为该值是不允许的,但出于某种原因,这并不完全适合我。没有关系的事实是此错误的重要性,而不仅仅是不允许尝试的值这一事实。

对于我的逻辑,是否有比 ValueError 更好的异常?

注意:我知道这个 ValueError 可能只是正确的答案,但我很好奇是否有更精确的东西,我在经历时可能无法看到与之相关的东西文档。

最佳答案

对我来说,不相关的实例听起来像是您想对错误类型的实例做些什么。

如果选择TypeError呢?

Raised when an operation or function is applied to an object of inappropriate type. The associated value is a string giving details about the type mismatch.

Source

根据您的评论进行编辑:

Documentation说:

ValueError Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.

这是正确的类型 - 正如您在评论中所述,但它的值不合适。 IndexError 无法描述情况 => 我会选择 ValueError

关于使用内置异常的 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20598310/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com