当我请求一个不存在的python对象的属性时,我得到了AttributeError,但是在error对象的字段中我没有找到请求的属性的名称。唯一提到请求属性名称的地方是错误的args
成员。你知道吗
在我看来,解析错误消息以获取丢失属性的名称有点麻烦。有没有办法在不解析错误消息的情况下获取缺少的属性的名称?你知道吗
演示:
class A:
def f(self):
print('in A')
class B:
pass
class C:
def f(self):
print('in C')
raise AttributeError()
def call_f(o):
try:
o.f()
except AttributeError as e:
# instead of e.args[0].endswith("'f'") it would be nice to do
# e.missing_attribute == 'f'
if e.args and e.args[0].endswith("'f'"):
print(e.args) # prints ("'B' object has no attribute 'f'",)
else: raise
if __name__ == '__main__':
a = A()
b = B()
c = C()
call_f(a)
call_f(b)
call_f(c)
目前还没有统一的方法。这个特性在PEP 473中被提出 它仍然是草稿
相关问题 更多 >
编程相关推荐