如何通过 Decorator 在后台捕获 AttributeError?
How to catch an AttributeError in Background through Decorator?
这会引发 AttributeError:
from functions import *
class Class:
def __init__(self):
self.name = 'Name'
@exception_handler
def do_stuff(self):
print('Stuff')
if __name__ == '__main__':
test = Class()
test.dooo_stuff()
AttributeError: 'Class' object has no attribute 'dooo_stuff'
我想用后台装饰器以某种方式捕获此属性错误。这样我就可以通知用户 class 方法名称已更改。
所以
try:
test = Class()
test.dooo_stuff()
except AttributeError:
print('info')
将不起作用,因为它不在后台。我想更改上面的错误消息以通知用户。
有什么办法吗?
谢谢
Python Data Model is very powerfull. You can customize attribute access with the dunder method __getattr__
:
Called when the default attribute access fails with an AttributeError [...] This method should either return the (computed) attribute value or raise an AttributeError exception.
虽然通常的用法是提供动态值(例如 mock or defaultdict 就是这样实现的),但也可以执行我们想要的任何代码,例如调用回调 :
def handler(attribute_error_name):
print(f"{attribute_error_name!r} does not exist")
class MyAPI:
def do_stuff(self):
return "done"
def __getattr__(self, item):
handler(item)
return lambda: None # if the return value is not callable, we get TypeError: 'NoneType' object is not callable
api = MyAPI()
print(api.do_stuff())
print(api.do_something_else())
产出
done
'do_something_else' does not exist
None
这会引发 AttributeError:
from functions import *
class Class:
def __init__(self):
self.name = 'Name'
@exception_handler
def do_stuff(self):
print('Stuff')
if __name__ == '__main__':
test = Class()
test.dooo_stuff()
AttributeError: 'Class' object has no attribute 'dooo_stuff'
我想用后台装饰器以某种方式捕获此属性错误。这样我就可以通知用户 class 方法名称已更改。
所以
try:
test = Class()
test.dooo_stuff()
except AttributeError:
print('info')
将不起作用,因为它不在后台。我想更改上面的错误消息以通知用户。 有什么办法吗? 谢谢
Python Data Model is very powerfull. You can customize attribute access with the dunder method __getattr__
:
Called when the default attribute access fails with an AttributeError [...] This method should either return the (computed) attribute value or raise an AttributeError exception.
虽然通常的用法是提供动态值(例如 mock or defaultdict 就是这样实现的),但也可以执行我们想要的任何代码,例如调用回调 :
def handler(attribute_error_name):
print(f"{attribute_error_name!r} does not exist")
class MyAPI:
def do_stuff(self):
return "done"
def __getattr__(self, item):
handler(item)
return lambda: None # if the return value is not callable, we get TypeError: 'NoneType' object is not callable
api = MyAPI()
print(api.do_stuff())
print(api.do_something_else())
产出
done
'do_something_else' does not exist
None