有没有我可以在Python中获得有关AttributeError异常的具体细节?

时间:2010-12-31 21:22:35

标签: python exception attributes error-handling

我正在尝试调用一个函数。其中一个参数是带有属性的变量(我知道因为我得到的AttributeError异常)。我不知道这个变量应该具有的确切属性,所以我想知道是否有某些方法我可以看到关于异常的一些额外细节,例如,它找不到哪个属性。感谢。

3 个答案:

答案 0 :(得分:13)

AttributeError通常标识缺少的属性。 e.g:

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()

这应该为您提供与异常相关的完整错误消息和回溯。

答案 1 :(得分:2)

回溯应该提醒您引发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

您甚至可以在help()上致电dir(为什么留给读者练习):

>>> 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.

如果没有这些......您可以随时查看代码,除非您已经由第三方提供了一些预编译模块,在这种情况下,您应该要求供应商提供更好的文档(比如一些单元测试!)!

答案 2 :(得分: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'