2010-10-21 39 views
0

是否有可能重新定義Python列表中Python列表的行爲,我的意思是,無需在Python源代碼中編寫任何東西?重新定義python列表

+3

你是什麼意思? – 2010-10-21 13:44:58

+0

你想達到什麼目的? – Rod 2010-10-21 13:57:49

回答

3

你總是可以創建自己的繼承自列表的子類。

一個例子(儘管你可能從來沒有想用這個):

class new_list(list): 
    '''A list that will return -1 for non-existent items.''' 
    def __getitem__(self, i): 
     if i >= len(self): 
      return -1 
     else: 
      return super(new_list, self).__getitem__(i) 

l = new_list([1,2,3]) 
l[2] #returns 3 just like a normal list 
l[3] #returns -1 instead of raising IndexError 
+0

在2.2之前的Python版本中,應該使用'UserList'。它仍然存在着向後兼容。 – 2010-10-21 14:31:41