Ich habe @ yutaka2487s "Python-Wörterbuch als Attribut zugänglich machen" gesehen und es schien, als könnte es auf eine andere Weise gemacht werden, also habe ich es versucht. Ich versuchte es.
Es ist eine einfache Möglichkeit, das Wörterbuch selbst (self
) in ein Attributwörterbuch ( __dict__
) umzuwandeln.
Alle Tests waren in Ordnung, aber wenn Sie irgendwelche Fallstricke haben, kommentieren Sie bitte.
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()
Testergebnisse
$ 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.