[英]Change instance attributes inside decorator
我已經搜索了這個問題,但是沒有找到我想要的答案。
基本上,我想將類構造函數包裝在try / except子句中,以便它忽略構造函數內部的特定類型的錯誤(但無論如何都要記錄並打印錯誤)。 我發現做到這一點的最好方法是用裝飾器包裝我的方法,因為我想在其他類中做同樣的事情,但是我不想一直重復相同的try / except子句。
但是, 對象必須記住構造函數中是否發生了異常 (將其保存在該對象的布爾屬性中),以便稍后在該對象調用特定方法時可以使用該信息。 因此,我嘗試執行以下代碼段中的操作:
def detectAndIgnoreErrors(fn):
def wrappedFunc(*args, **kwargs):
try:
fn(*args, **kwargs)
self.HasAnExceptionOccurredInInit = False
except KeyError as e:
self.HasAnExceptionOccurredInInit = True
# Log and print exception
except RuntimeError as e:
self.HasAnExceptionOccurredInInit = True
# Log and print exception
return wrappedFunc
class Foo(FooSuperclass):
@detectAndIgnoreErrors
def __init__(self):
# Do stuff that may raise exceptions
pass
def doStuff(self):
if self.HasAnExceptionOccurredInInit:
# Do stuff
pass
else:
# Do other stuff
pass
fooInstance = Foo()
fooInstance.doStuff()
這里的想法是讓對象忽略構造函數中的錯誤,然后在調用doStuff()
方法時,對象會記住HasAnExceptionOccurredInInit
是否發生異常,並相應地調整其行為。 但是,解釋器說未定義self
名稱(這很有意義,因為我試圖在類范圍之外訪問它)。
然后,我嘗試將裝飾器作為類成員放置,然后再嘗試將其作為Foo的父類中的類成員放置,但是這些替代方法均無效。
經過研究后,我意識到裝飾器是在定義時解決的,而不是在執行時解決的,因此無法以這種方式使用self
,因此我不知道該如何解決這個問題。
如果有人知道如何解決這個問題(或者是一個更好的解決方案,而不是裝飾器),將不勝感激。
包裝的函數沒有名為self
的參數; 如果要假設fn
是一種方法,則需要特別指定。
def detectAndIgnoreErrors(fn):
def wrappedFunc(self, *args, **kwargs):
try:
fn(self, *args, **kwargs)
self.HasAnExceptionOccurredInInit = False
except KeyError as e:
self.HasAnExceptionOccurredInInit = True
# Log and print exception
except RuntimeError as e:
self.HasAnExceptionOccurredInInit = True
# Log and print exception
return wrappedFunc
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.