2011-12-29 109 views
0

這裏是我的代碼:引發異常問題

class longInputException(Exception): 
    def __init__(self, length, max): 
     Exception.__init__(self) 
     self.length = len(length) 
     self.max = max 

try: 
    max = 3 
    s = raw_input('Enter something-->') 
    if len(s) > max: 
     raise longInputException(s, max) 

except longInputException, x: 
    print 'longInputException: the input was of length %d, \ 
was expecting less than or equal to %d' % (x.length, x.max) 

else: 
    print 'No exception was raised.' 

我不明白的是爲什麼xlongInputExceptionexcept語句中使用。爲什麼不直接在替換元組中使用self

回答

3

self是當前對象__init__()方法的名字(因爲你已經提供self__init__()的定義中的第一個參數),它是不是它的外部訪問。

您也可以選擇做這樣的事情(雖然這不是東西你應該做的,因爲這可能會混淆人們瞭解哪些變量是):

except longInputException, self: 
    print 'longInputException: the input was of length %d, \ 
was expecting less than or equal to %d' % (self.length, self.max) 

else: 
    print 'No exception was raised.' 

是否回答你的問題?

您可以通過閱讀關於Python中的閉包和命名空間來了解更多信息。

0

如果你嘗試......除了聲明是在另一個類的一個實例,你在使用的「自我」除了聲明,「自我」就指的是實例化類,而不是實例化異常類。

0

我想這是因爲你不知道你指的是異常的哪個實例。無論如何,你通常只在對象內部使用'self'。