2012-04-05 66 views
1

可以說我有代碼:類中的模塊

class NoneDict(dict): 
    def __getitem__(self, name): 
     try: 
       return super(NoneDict, self).__getitem__(name) 
     except: 
       return None 

我希望人們能夠在不進行編寫​​這些代碼來創建一個NoneDict對象。我嘗試將它包含在模塊中,然後鍵入:

import nonedict 
foo = NoneDict() 

但它沒有工作。我怎樣才能做到這一點,以便有人可以導入模塊,然後能夠創建一個nonedict而不輸入所有的代碼?

+1

你從nonedict進口NoneDict'嘗試'? – 2012-04-05 02:44:52

回答

3
import nonedict 
foo = nonedict.NoneDict() 

from nonedict import NoneDict 
foo = NoneDict() 

或(感謝@Joel科內特)

from nonedict import NoneDict as nd 
foo = nd() 
+0

你也可以做'從nonedict導入NoneDict as nd' – 2012-04-05 03:39:35