J'ai vu "[Rendre le dictionnaire Python accessible en tant qu'attribut] de @ yutaka2487](http://qiita.com/yutaka2487/items/a7c57960c2b6befa5edf)" et il semblait que cela pouvait être fait d'une autre manière, alors je l'ai essayé. Je l'ai essayé.
C'est un moyen simple de transformer le dictionnaire lui-même (self
) en un dictionnaire d'attributs ( __dict__
).
Tous les tests étaient ok, mais si vous avez des pièges, veuillez commenter
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()
résultats de test
$ 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.