8
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

別法: Pythonの辞書を属性としてアクセスできるようにする

Last updated at Posted at 2017-02-18

@yutaka2487 さんの「Pythonの辞書を属性としてアクセスできるようにする」を拝見して、別の方法でもできそうに思えたので試してみました。
辞書自身(self)を属性辞書(__dict__)にもしてしまうという単純な方法です。
テストは全部okでしたが、何か落とし穴などありましたら是非コメントください。

attrdict.py
class attrdict(dict):
    '''A dictionary that can also access attributes using its keyword.

    >>> ad = attrdict(a=1, b=2)
    >>> sorted(ad.items())
    [('a', 1), ('b', 2)]
    >>> ad['a'], ad.a
    (1, 1)
    >>> ad['b'], ad.b
    (2, 2)
    >>> ad['a'] = 3
    >>> ad['a'], ad.a
    (3, 3)
    >>> ad.b = 4
    >>> ad['b'], ad.b
    (4, 4)
    >>> ad['c'] = 5
    >>> ad['c'], ad.c
    (5, 5)
    >>> ad.d = 6
    >>> ad['d'], ad.d
    (6, 6)
    >>> sorted(ad.items())
    [('a', 3), ('b', 4), ('c', 5), ('d', 6)]
    '''

    def __init__(self, *args, **kwargs):
        dict.__init__(self, *args, **kwargs)
        self.__dict__ = self

if __name__ == '__main__':
    import doctest
    doctest.testmod()
テスト結果
$ python attrdict.py -v
Trying:
    ad = attrdict(a=1, b=2)
Expecting nothing
ok
Trying:
    sorted(ad.items())
Expecting:
    [('a', 1), ('b', 2)]
ok
Trying:
    ad['a'], ad.a
Expecting:
    (1, 1)
ok
Trying:
    ad['b'], ad.b
Expecting:
    (2, 2)
ok
Trying:
    ad['a'] = 3
Expecting nothing
ok
Trying:
    ad['a'], ad.a
Expecting:
    (3, 3)
ok
Trying:
    ad.b = 4
Expecting nothing
ok
Trying:
    ad['b'], ad.b
Expecting:
    (4, 4)
ok
Trying:
    ad['c'] = 5
Expecting nothing
ok
Trying:
    ad['c'], ad.c
Expecting:
    (5, 5)
ok
Trying:
    ad.d = 6
Expecting nothing
ok
Trying:
    ad['d'], ad.d
Expecting:
    (6, 6)
ok
Trying:
    sorted(ad.items())
Expecting:
    [('a', 3), ('b', 4), ('c', 5), ('d', 6)]
ok
2 items had no tests:
    __main__
    __main__.attrdict.__init__
1 items passed all tests:
  13 tests in __main__.attrdict
13 tests in 3 items.
13 passed and 0 failed.
Test passed.
8
8
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?