有什么办法可以获取有关 Python 中 AttributeError 异常的具体详细信息吗?

发布于 2024-10-09 21:17:11 字数 131 浏览 0 评论 0原文

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

I'm trying to call a function. One of the parameters is a variable with attributes (which I know because of the AttributeError exception I got). I don't know the exact attributes this variable is supposed to have, so I was wondering if there was some way I can see some extra details about the exception, for example, which attribute it couldn't find. Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

浅笑轻吟梦一曲 2024-10-16 21:17:11

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

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

AttributeError typically identifies the missing attribute. e.g.:

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

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

When I run that, I see:

$ 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'

That's pretty explicit. If you're not seeing something like that, please post the exact error you're seeing.

EDIT

If you need to force the printing of an exception (for whatever reason), you can do this:

import traceback

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

That should give you the full error message and traceback associated with the exception.

浅语花开 2024-10-16 21:17:11

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

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

The traceback should alert you to the attribute access that raised the AttributeError exception:

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

Alternatively, convert the Exception to str:

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

If you want to get a list of the attributes available on an object, try dir() or 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

You can even call help() on dir (why is left as an exercise for the reader):

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

Failing these... you could always look at the code, unless you've been provided some precompiled module by a third-party, in which case you should demand better documentation (say some unit tests!) from your supplier!

我不会写诗 2024-10-16 21:17:11

通常 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'

Usually AttributeError carries some information about this with it:

#!/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'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文