class MyError(Exception): def __init__(self, line, file): self.line = line self.file = file def logerr(self): with open('Error.log', 'a') as logfile: print(self, file=logfile) def __str__(self): return "format failed: %s at %s" % (self.file, self.line) def format(): raise MyError(42, "a.json") try: format() except MyError as E: E.logerr()
def logerr(self): with open('Error.log', 'a') as logfile: print(self, file=logfile),这里的print会自动调用下面的__str__美化,print底层用了str(),直接调用对象的__str__
def __str__(self):
return "format failed: %s at %s" % (self.file, self.line)