8

属性の取得と設定に関して、Python 辞書を JavaScript オブジェクトのように動作させるユーティリティ クラスがあります。

class DotDict(dict):
    """
    a dictionary that supports dot notation 
    as well as dictionary access notation 
    usage: d = DotDict() or d = DotDict({'val1':'first'})
    set attributes: d.val2 = 'second' or d['val2'] = 'second'
    get attributes: d.val2 or d['val2']
    """
    __getattr__ = dict.__getitem__
    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__

ネストされた辞書も DotDict() インスタンスに変換するようにしたいと思います。__init__orでこのようなことができることを望んでいましたが、うまくいくものは__new__思いつきませんでした:

def __init__(self, dct):
    for key in dct.keys():
        if hasattr(dct[key], 'keys'):
            dct[key] = DotDict(dct[key])

ネストされた辞書を再帰的に DotDict() インスタンスに変換するにはどうすればよいですか?

>>> dct = {'scalar_value':1, 'nested_dict':{'value':2}}
>>> dct = DotDict(dct)

>>> print dct
{'scalar_value': 1, 'nested_dict': {'value': 2}}

>>> print type(dct)
<class '__main__.DotDict'>

>>> print type(dct['nested_dict'])
<type 'dict'>
4

4 に答える 4

13

コンストラクターで値をコピーしている場所がわかりません。そのため、ここで DotDict は常に空です。キーの割り当てを追加すると、うまくいきました:

class DotDict(dict):
    """
    a dictionary that supports dot notation 
    as well as dictionary access notation 
    usage: d = DotDict() or d = DotDict({'val1':'first'})
    set attributes: d.val2 = 'second' or d['val2'] = 'second'
    get attributes: d.val2 or d['val2']
    """
    __getattr__ = dict.__getitem__
    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__

    def __init__(self, dct):
        for key, value in dct.items():
            if hasattr(value, 'keys'):
                value = DotDict(value)
            self[key] = value


dct = {'scalar_value':1, 'nested_dict':{'value':2, 'nested_nested': {'x': 21}}}
dct = DotDict(dct)

print dct.nested_dict.nested_nested.x

他の開発者にとって数え切れないほどの驚きの原因は言うまでもなく、少し危険でエラーが発生しやすいように見えますが、機能しているようです.

于 2012-11-22T21:58:19.460 に答える