無效。檢查Brian anwser。
好吧,我剛剛纔:
for x in Exception("test") :
print x
....:
....:
test
不要打擾;-)
無論如何,這是很好的瞭解。
編輯:期待的意見,我覺得像添加一些解釋。
例外包含您實例化過程中傳遞的消息:
raise Exception("test")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Exception: test
公平地說,消息是什麼定義異常最好的,所以STR()返回它:
print Exception("test")
test
現在,在異常情況以外的情況下,異常被隱式轉換爲字符串。
所以,當我做的:
for x in Exception("test") :
print x
我遍歷字符串 「測試」。
當我做:
for x in Exception() :
print x
我遍歷一個空字符串。棘手。因爲當涉及到我的問題:
try :
thing.merge(ExceptionLikeObject)
except TypeError :
...
這不會引發任何事情,因爲ExceptionLikeObject被視爲一個字符串。
現在,我們知道如何,但我仍然不是爲什麼。也許內置的Exception繼承自內建的String?因爲據我所知:
- 加入str不會使任何對象迭代。
- 我繞過這個問題,因爲overloding iter,使它引發TypeError!
不再是問題,但仍然是一個謎。
其實它不是把它當作一個字符串,它是把它當作參數元組。即list(Exception(「test」))== [「test」],而不是[「t」,「e」,「s」,「t」]。同樣列表(Exception(1,2))== [1,2]。有關這可能是爲什麼的猜測,請參閱下面的答案。 – Brian 2008-11-03 15:22:53