-1
class MyException(Exception):
def __str__(self):
return self.args[0]
def DoWork():
raise MyException("My hoverboard is full of eels")
pass
if __name__ == '__main__':
try:
DoWork()
except MyException as ex:
print("This will get printed: " + str(ex)) #Line1
print("This will not get printed and will raise exception: " + ex) #Line2
爲什麼異常需要,如圖2號線在1號線在理想情況下它應該工作的一個顯式轉換。 注:我已經嘗試了兩種 - 從MyException類刪除str,並添加str;他們都沒有工作。 請幫忙。Python3:爲什麼異常需要顯式轉換而打印的消息
那麼爲什麼打印(EX)的作品?即使是使用隱式轉換。 – AshishTheDev
'print()'不使用隱式轉換,它將一個對象作爲它的參數(確保它最終調用'__str__'或'__repr__',但這不是真正相關的)。 'x + y'調用'x .__ add __(y)',當'x'是'str','y'需要'str'或者你會得到一個異常。如果你真的希望'str + MyType'正常工作,你可以在'MyType'中實現'__add__'和'__radd__',並使它們與'str'參數一起工作,但這太可怕了。 – verdesmarald