2016-09-19 59 views
0

基本上我希望能夠採取class江湖醫生dict(如我下面的例子DICT),並添加一個MixIn,讓我訪問DICT的值的屬性......如如何爲python「字典式」類創建一個泛化AttrDict Mixin?

print purchase.price # instead of purchase["price"] 

背景:我有各種不同的數據庫表(而不僅僅是DICT例子)那樣子(& 嘎嘎)像dict(如bsddb。),我想定義(再使用)的標準AttrDictMixIn。 (所以應避免使用的代碼樣板剪切/粘貼)

# First try using a std dict 
class AttrDict(dict): 
    def __init__(self, *args, **kwargs): 
     self.__dict__ = self 
     super(AttrDict, self).__init__(*args, **kwargs) 

test1=AttrDict() 
test1.x="111" 
print 1,test1 

# Next derive a crude UPPER dict 
class DICT(dict): # EXAMPLE ONLY 
    def __getitem__(self,key): 
    return super(DICT,self).__getitem__(key.upper()) 

    def __setitem__(self,key,value): 
    return super(DICT,self).__setitem__(key.upper(),value) 

test2=DICT() 
test2["x"]="222" 
print 2,test2 

# Next define a AttrDict MixIn 
class AttrDictMixIn(object): # This is what I want to work... 
    def __init__(self, *args, **kwargs): 
     self.__dict__ = self 
     return super(AttrDict, self).__init__(*args, **kwargs) 

# Apply the MixIn to DICT 
class AttrDICT(DICT,AttrDictMixIn): pass 

test3=AttrDICT() 
test3.x="333.xxx" 
test3["y"]="333.yyy" 
print 3,test3,"X is missing" 
print 4,"test3.x:",test3.x,"OK" 
print 5,"test3['y']:",test3["y"],"OK" 
print 6,"test3.y:",test3.y,"DUD" 
print 7,"test3['x']:",test3["x"],"DUD" 

輸出:

1 {'x': '111'} 
2 {'X': '222'} 
3 {'Y': '333.yyy'} X is missing 
4 test3.x: 333.xxx OK 
5 test3['y']: 333.yyy OK 
6 test3.y: 
Traceback (most recent call last): 
    File "x.py", line 39, in <module> 
    print 6,"test3.y:",test3.y,"DUD" 
AttributeError: 'AttrDICT' object has no attribute 'y' 

我懷疑我做的一些小事錯...提示歡迎。 (以及類似python MixIns的一些參考示例的指針也可能有所幫助)

編輯:解釋爲什麼行self.__dict__ = self中斷多重繼承將不勝感激。

+1

你是什麼意思*但是它不工作*?你想發佈你的錯誤追溯? –

+0

剛剛添加了「X is missing」的評論和回溯。 – NevilleDNZ

回答

0

像這樣實現:

class AttrDictMixin(object): 
    def __getattr__(self, name): 
     return self[name] 
    def __setattr__(self, name, value): 
     self[name] = value 
    def __delattr__(self, name): 
     del self[name] 

在訪問屬性,設置,或刪除 - __getattr____setattr____delattr__相應調用。

記住混入應該來在繼承基類前:

class AttrDict(AttrDictMixin, DICT): pass