这两种错误有什么区别?何时使用它们中的每一个?
请您参考如下方法:
属性是函数、类或模块的属性,如果找不到属性,则会引发属性错误。
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'
