arasında istenmeyen etkileşim Ben Python __getattr__()
ile birlikte bir @property
büyüdü AttributeErrors
ile ilgili bir sorun:AttributeErrors: @ özellik ve __getattr__
örnek kod: Benim durumumda
>>> 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'
, bu bir son derece yanıltıcı hata mesajı, çünkü deeply_nested_factory_fn()
bir hataya sahip olduğu gerçeğini gizler. Tadhg McDonald-Jensen yanıtında fikrine dayanarak
, benim şu anda en iyi çözüm şudur.
__main__.
önekinden
AttributeError
'a ve
attributeErrorCatcher
referansından geri izlemeye nasıl gidileceği ile ilgili ipuçları çok takdir edilecektir. Eğer münhasıran yeni tarzı sınıfları kullanmak isteyen iseniz
>>> 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'
'__main__' kısmını kaldırmak için sınıf tanımında '__qualname__ =" AttributeError "' yapmak zorundasınız ama bana güvenin, ** yapmak değil ** hata sadece AttributeError demek istemez, çünkü şaşkınlık riskiyle karşılaşırsınız Neden AttributeError 'dışındaki heck bir AttributeError yakalamadı. –