python中缺失值的标准异常是什么?

Typ*_*hon 4 python exception

在缺少正确执行函数的值的情况下,应该使用哪个标准 python 异常(如果有)?TypeError并且ValueError似乎很好的候选人给我,但根据文档(我的斜体字):

传递错误类型的参数(例如,listint预期为an 时传递 a )应导致 a TypeError,但传递具有错误值(例如超出预期边界的数字)的参数应导致 a ValueError

ValueError:当操作或函数接收到类型正确但值不合适的参数时引发,并且这种情况没有用更精确的异常(例如 IndexError )描述。

在我看来,这些描述都不能完全抓住缺失值的概念。但标准中的其他例外似乎也没有接近。

这是一个例子。类型的对象myclass可以通过两种不同的方式实例化,每种方式都需要一个特定的参数。如果两者均未提供,则 init 将失败。

class myclass(object):
    def __init__(self,firstparam=None,secondparam=None):
        if firstparam:
             self.firstinit()
        elif secondparam:
             self.secondinit()
        else:
           #What to put here ?
           raise Exception("Missing value for myclass")

if __name__=="__main__":
    #oops, forgot to specify a parameter here !
    myobj=myclass()
    
Run Code Online (Sandbox Code Playgroud)

当然,我知道MissingValueError在编写库时我总是可以实现自己的异常子类。我问这个问题是为了不重复标准中可能已经存在的东西。

len*_*nik 6

正确的例外是TypeError

>>> def a(b,c) : print b,c
... 
>>> a(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: a() takes exactly 2 arguments (1 given)
>>> 
Run Code Online (Sandbox Code Playgroud)

作为旁注,我建议不要为所需参数提供默认值,因此您班级的用户会清楚地了解他必须提供一些。