2012-12-13 26 views
9

我一直在用我的代碼如下:IPython的自定義字典類標籤完成

class Structure(dict,object): 
""" A 'fancy' dictionary that provides 'MatLab' structure-like 
referencing. 

""" 
def __getattr__(self, attr): 
    # Fake a __getstate__ method that returns None 
    if attr == "__getstate__": 
     return lambda: None 
    return self[attr] 

def __setattr__(self, attr, value): 
    self[attr] = value 

def set_with_dict(self, D): 
    """ set attributes with a dict """ 
    for k in D.keys(): 
     self.__setattr__(k, D[k]) 

總而言之它適合我的目的,但我注意到,只有這樣,tab完成的工作是方法在從Structure繼承的另一個自定義類中,而不是用於屬性。我還做了這個測試,我發現結果有些奇怪:

In [2]: d = Structure() 
In [3]: d.this = 'that' 
In [4]: d.this 
Out[4]: 'that' 
In [5]: d.th<tab> 
NOTHING HAPPENS 

In [6]: class T(): 
    ...:  pass 
    ...: 

In [7]: t = T() 
In [8]: t.this = 'cheese' 
In [9]: t.th<tab> 
COMPLETES TO t.this 
Out[9]: 'cheese' 

我需要添加到我的類來獲取標籤完成,爲屬性工作?

+0

如果你想點接入的*代替*支架的索引,而不是*除了*它,你可以使用'object'的空子類。 Python對象默認是「打開」的。由於'dict'(和大多數標準庫類)都是新建的,因此''dict''和'object'都是多餘的,'x.set_with_dict()'可以替換爲'x .__ dict __。update()' – millimoose

+0

。樣式類,並已從'object'繼承。 – millimoose

+0

關於多繼承的好處。但是,我確實希望將_both_括號和點訪問到我的密鑰。我試圖將我的代碼切換到使用純Python字典,但仍然有相當一些依賴點訪問的地方... – John

回答