假设我有一个类,我希望异常由装饰器处理:
class A:
def __init__(self, start: bool):
self.start = start
def enc(self, data):
try:
if self.start:
return data.encode()
return 'ok'
except AttributeError:
raise Exception('oh no')
def dec(self, data):
try:
if self.start:
return data.decode()
return 'ok'
except AttributeError:
raise Exception('oh no')
我想添加一个decorator来处理异常:如下所示:
(这行不通, @A.type_exc_handler NameError: name 'A' is not defined
):
class A:
def __init__(self, start: bool):
self.start = start
def type_exc_handler(self, func):
def inner(self, *args,**kwargs):
try:
func(self, *args,**kwargs)
except AttributeError:
raise TypeError(f"oh no")
return inner
@A.type_exc_handler
def enc(self, data):
if self.start:
return data.encode()
return 'ok'
@A.type_exc_handler
def dec(self, data):
if self.start:
return data.decode()
return 'ok'
我怎样才能做到这一点?
暂无答案!
目前还没有任何答案,快来回答吧!