2016-09-19 8 views
0

基本的に私はdictようclassその鳴く(例えば私の例以下DICT)に乗り、私は属性としてDICTの値にアクセスすることを可能にするMixInを追加できるようにしたい...などPythonの "dict-style"クラス用の一般化AttrDict Mixinはどのように作成されますか?

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

背景:私は(。bsddbなど)dictのように(& いんちき)を見て、様々な異なるデータベーステーブル(だけでなく、DICT例)を持っていると私は(使用当時)を定義する標準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の参考例へのポインタも役に立ちます)

edit:なぜ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 
関連する問題