2016-01-29 38 views
4

我最近了解到如何在Python中創建自定義異常並將它們實現爲類。我試圖添加一個額外的參數到我的例外中以獲得更多清晰度,並且似乎無法正確完成格式設置。將參數傳遞到自定義異常中

這裏就是我試圖:

class NonIntError(Exception): 
    pass 

class intlist(List): 

    def __init__(self, lst = []): 

     for item in lst: 
      #throws error if list contains something other that int 
      if type(item) != int: 
       raise NonIntError(item, 'not an int') 

      else: 
       self.append(item) 

預期結果

il = intlist([1,2,3,'apple']) 

>>> NonIntError: apple not an int 

結果與錯誤

il = intlist([1,2,3,'apple']) 

>>> NonIntError: ('apple', 'not an int') 

重申發佈我的問題,我想知道如何使我的例外看起來像預期的結果。

回答

3

您正在使用兩個自變量,item和字符串'not an int'初始化您的自定義異常。當你初始化多個參數之外,* ARGS將顯示爲一個元組:

>>> raise NonIntError('hi', 1, [1,2,3]) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
__main__.NonIntError: ('hi', 1, [1, 2, 3]) 

爲了得到你想要的結果,通過只有一個字符串,即:

>>> item = 'apple' 
>>> raise NonIntError(item + ' not an int') 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
__main__.NonIntError: apple not an int 
1

根據您的類和timgeb的回答,我有更好的回答:

當您檢查列表中的元素是否爲int,我建議你:

class intlist(object): 

    def __init__(self, lst = []): 
     not_int_list = filter(lambda x: not isinstance(x, int), lst) 
     if not_int_list: 
      if len(not_int_list) > 1: 
       items = ', '.join(not_int_list) 
       raise NonIntError(items + ' are not int type') 
      item = not_int_list.pop() 
      raise NonIntError(item + ' is not int type') 

il = intlist([1,2,3,'apple']),它將返回:

>>> NonIntError: apple is not int type 

il = intlist([1,2,3,'apple','banana']),它將返回:

>>> NonIntError: apple, banana are not int type 

它加強可讀當列表包括單個或多個非INT元件將返回適當的錯誤消息。


說明:

not_int_list = filter(lambda x: not isinstance(x, int), lst) 

使用filterisinstance將協助您進行編碼讀取類對象和檢查機制。

if len(not_int_list) > 1: 
    items = ', '.join(not_int_list) 
    raise NonIntError(items + ' are not int type') 
item = not_int_list.pop() 
raise NonIntError(item + ' is not int type') 

當列表中有單個或多個無效元素時,它將返回相應的錯誤消息。

NonIntError(items + ' are not int type') 

有從timgeb的答案。沒有必要再解釋了。

相關問題