【发布时间】:2016-08-03 04:07:35
【问题描述】:
我对@987654322@ 中的AttributeErrors 与python 中的__getattr__() 结合存在问题:
示例代码:
>>> def deeply_nested_factory_fn():
... a = 2
... return a.invalid_attr
...
>>> class Test(object):
... def __getattr__(self, name):
... if name == 'abc':
... return 'abc'
... raise AttributeError("'Test' object has no attribute '%s'" % name)
... @property
... def my_prop(self):
... return deeply_nested_factory_fn()
...
>>> test = Test()
>>> test.my_prop
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in __getattr__
AttributeError: 'Test' object has no attribute 'my_prop'
就我而言,这是一条高度误导的错误消息,因为它隐藏了deeply_nested_factory_fn() 有错误的事实。
根据 Tadhg McDonald-Jensen 的回答,我目前最好的解决方案如下。任何关于如何摆脱 AttributeError 前缀的 __main__. 以及回溯中对 attributeErrorCatcher 的引用的提示将不胜感激。
>>> def catchAttributeErrors(func):
... AttributeError_org = AttributeError
... def attributeErrorCatcher(*args, **kwargs):
... try:
... return func(*args, **kwargs)
... except AttributeError_org as e:
... import sys
... class AttributeError(Exception):
... pass
... etype, value, tb = sys.exc_info()
... raise AttributeError(e).with_traceback(tb.tb_next) from None
... return attributeErrorCatcher
...
>>> def deeply_nested_factory_fn():
... a = 2
... return a.invalid_attr
...
>>> class Test(object):
... def __getattr__(self, name):
... if name == 'abc':
... # computing come other attributes
... return 'abc'
... raise AttributeError("'Test' object has no attribute '%s'" % name)
... @property
... @catchAttributeErrors
... def my_prop(self):
... return deeply_nested_factory_fn()
...
>>> class Test1(object):
... def __init__(self):
... test = Test()
... test.my_prop
...
>>> test1 = Test1()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in __init__
File "<stdin>", line 11, in attributeErrorCatcher
File "<stdin>", line 10, in my_prop
File "<stdin>", line 3, in deeply_nested_factory_fn
__main__.AttributeError: 'int' object has no attribute 'invalid_attr'
【问题讨论】:
-
您必须在类定义中执行
__qualname__ = "AttributeError"才能删除__main__部分,但请相信我,您确实不希望错误只是说 AttributeError 因为那时您可能会感到困惑,为什么except AttributeError没有捕获 AttributeError。
标签: python properties attributeerror getattr