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

Krz*_*iak 8 python error-handling attributes exception

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

Bri*_*per 15

AttributeError通常标识缺少的属性.例如:

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

f = Foo()
print(f.a)
print(f.b)
Run Code Online (Sandbox Code Playgroud)

当我跑步时,我看到:

$ 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'
Run Code Online (Sandbox Code Playgroud)

这很明确.如果您没有看到类似的内容,请发布看到的确切错误.

编辑

如果您需要强制打印异常(无论出于何种原因),您可以这样做:

import traceback

try:
    # call function that gets AttributeError
except AttributeError:
    traceback.print_exc()
Run Code Online (Sandbox Code Playgroud)

这应该给你完整的错误消息和与异常相关的回溯.