Python中的NameError和AttributeError有什么区别?

时间:2012-08-12 11:06:41

标签: python exception-handling

这两种错误有什么区别?何时使用它们中的每一个?

3 个答案:

答案 0 :(得分:6)

属性是函数或类或模块的属性,如果找不到属性,则它会引发attribute error

NameError与变量有关。

>>> x=2
>>> y=3
>>> z    #z is not defined so NameError

Traceback (most recent call last):
  File "<pyshell#136>", line 1, in <module>
    z
NameError: name 'z' is not defined

>>> def f():pass

>>> f.x=2 #define an attribue of f
>>> f.x
2
>>> f.y   #f has no attribute named y

Traceback (most recent call last):
  File "<pyshell#141>", line 1, in <module>
    f.y
AttributeError: 'function' object has no attribute 'y'

>>> import math   #a module  

>>> math.sin(90) #sin() is an attribute of math
0.8939966636005579

>>> math.cosx(90)  #but cosx() is not an attribute of math

Traceback (most recent call last):
  File "<pyshell#145>", line 1, in <module>
    math.cosx(90)
AttributeError: 'module' object has no attribute 'cosx'

答案 1 :(得分:2)

docs我认为该文本非常自我解释。

<强> NameError 未找到本地或全局名称时引发。这仅适用于不合格的名称。关联的值是一条错误消息,其中包含无法找到的名称。

<强> AttributeError的 当属性引用(请参阅属性引用)或赋值失败时引发。 (当一个对象根本不支持属性引用或属性赋值时,会引发TypeError。)

在上面的示例中,当您尝试访问非限定名称(本地或全局)时,对z的引用会引发NameError

在上一个示例中,math.cosx是一个虚线访问(属性引用),在这种情况下是数学模块的属性,因此引发了AttributeError

答案 2 :(得分:0)

如果您尝试访问之前未定义或分配的变量,则Python会引发名称。当您尝试访问之前未分配或定义的实例的实例变量时,会引发AttributeError。

http://docs.python.org/library/exceptions.html