有没有办法获取Python中AttributeError异常的具体细节?

10 投票
3 回答
15319 浏览
提问于 2025-04-16 09:15

我正在尝试调用一个函数。其中一个参数是一个有属性的变量(我知道这一点是因为我遇到了一个叫做AttributeError的错误)。不过我不知道这个变量应该具有什么具体的属性,所以我想知道有没有办法查看这个错误的更多细节,比如说,它找不到哪个属性。谢谢。

3 个回答

0

通常,AttributeError 会带有一些相关的信息:

#!/usr/bin/env python

class SomeClass(object):
    pass

if __name__ == '__main__':
    sc = SomeClass()
    print sc.fail

#   Traceback (most recent call last):
#   File "4572362.py", line 8, in <module>
#     print sc.fail
# AttributeError: 'SomeClass' object has no attribute 'fail'
3

错误追踪信息会告诉你哪个属性访问导致了 AttributeError 异常的出现:

>>> f.b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: Foo instance has no attribute 'b'

另外,你可以把 Exception 转换成 str(字符串):

>>> try:
...     f.b
... except AttributeError, e:
...     print e
... 
Foo instance has no attribute 'b'

如果你想查看一个对象上有哪些可用的属性,可以试试 dir() 或者 help()

>>> dir(f)
['__doc__', '__init__', '__module__', 'a']

>>> help(str)
Help on class str in module __builtin__:

class str(basestring)
 |  str(object) -> string
 |  
 |  Return a nice string representation of the object.
 |  If the argument is a string, the return value is the same object.
 |  
 |  Method resolution order:
 |      str
 |      basestring
 |      object
 |  
 |  Methods defined here:
 |  
 |  __add__(...)
 |      x.__add__(y) <==> x+y
 |  
[...]
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __new__ = <built-in method __new__ of type object>
 |      T.__new__(S, ...) -> a new object with type S, a subtype of T

你甚至可以对 dir 使用 help()(为什么这样做留给你自己去探索):

>>> help(dir)
Help on built-in function dir in module __builtin__:

dir(...)

dir([object]) -> list of strings

If called without an argument, return the names in the current scope.
Else, return an alphabetized list of names comprising (some of) the attributes
of the given object, and of attributes reachable from it.
If the object supplies a method named __dir__, it will be used; otherwise
the default dir() logic is used and returns:
  for a module object: the module's attributes.
  for a class object:  its attributes, and recursively the attributes
    of its bases.
  for any other object: its attributes, its class's attributes, and
    recursively the attributes of its class's base classes.

如果这些方法都不行……你可以看看代码,除非你是用第三方提供的预编译模块,这种情况下你应该向供应商要求更好的文档(比如一些单元测试!)

16

AttributeError 通常是用来表示缺少某个属性的错误。例如:

class Foo:
    def __init__(self):
        self.a = 1

f = Foo()
print(f.a)
print(f.b)

当我运行这个时,我看到:

$ python foo.py
1
Traceback (most recent call last):
  File "foo.py", line 10, in <module>
    print(f.b)
AttributeError: Foo instance has no attribute 'b'

这个错误信息很明确。如果你没有看到类似的内容,请把你看到的具体错误信息发出来。

编辑

如果你需要强制打印出一个异常(不管是什么原因),你可以这样做:

import traceback

try:
    # call function that gets AttributeError
except AttributeError:
    traceback.print_exc()

这样可以让你看到完整的错误信息和与这个异常相关的追踪信息。

撰写回答