来源:GPT写的。
目前网络上的教法涉及到调用类内方法比较少,其实核心是在于wrapper和func需要同时传入self。
def catch_error(func):
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
try:
return func(self, *args, **kwargs)
except Exception as e:
traceback.print_exc()
self.my_method_report(str(e))
return wrapper
class MyClass:
def my_method_report(self, msg):
print("report~")
@catch_error
def my_method(self, *args, **kwargs):
print("my_method~")
raise NotADirectoryError
@catch_error
def another_method(self, *args, **kwargs):
print("another_method~")
raise FileNotFoundError
if __name__ == '__main__':
c = MyClass ()
c.my_method()