我正在寫一個名爲Rule
的類的方法check
,它可以拋出RuleEnforced
異常,其中的錯誤消息包含Rule
的字符串表示形式,並將其引發。這是怎麼回事現在已經實現:在Python中,是否有對Exception的提升者的引用?
class RuleEnforced(Exception):
def __init__(self, rule, reason):
message = "The rule {rule} failed for the following reason: {reason}".format(rule=rule, reason=reason)
super(RuleEnforced, self).__init__(message)
class Rule(object):
def check(self):
raise RuleEnforced(rule=self, reason="Why not?")
的rule=self
參數始終是相同的,但是,我正在尋找一種方法,使使用的代碼更簡潔,在例外,像「self.caller.__class__
「(用僞代碼)。有什麼辦法可以做到這一點?
是的,在回溯。然而,這並不像傳入「自我」那樣容易。 –