2013-01-07 28 views
1

我想覆蓋Python中類dict的一個方法,簡單的方法如下:update。假設我想創建一個MyDict類,它與標準dict相同,不同之處在於它可以更新爲dict,它必須包含至少10個元素。覆蓋方法不會陷入無限遞歸

因此,我將繼續這樣的:

def update(self, newdict): 
    if len(newdict) <= 10: raise Exception 
    self.update(newdict) 

但到update內通話,顯然Python會自動調用重寫的功能,而不是原來的一個。有沒有辦法避免這種情況,而不是簡單地改變函數名稱?

回答

4

您需要在超類上調用update,將子類的實例作爲self提供。

def update(self, newdict): 
    if len(newdict) <= 10: raise Exception 
    dict.update(self, newdict) 

您還可以使用super()確定在運行時超:

def update(self, newdict): 
    if len(newdict) <= 10: raise Exception 
    super(MyDict, self).update(newdict) 

在Python 3,你可以省略參數super()

def update(self, newdict): 
    if len(newdict) <= 10: raise Exception 
    super().update(newdict) 
+0

爲Python 3.x的,你可以簡單地使用'超()。更新(newdict)' – 2013-01-07 16:12:26

+0

感謝@Mahi。添加。 – zigg

0

你從繼承字典類?使用超級功能

super(MyDict, self).update 

應該做的伎倆

+1

您可能需要在'update'調用中使用一些參數。 ;-) – zigg

+0

我可能會這樣做,但我太累了:-( – volcano