File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change 1+ #!/usr/bin/env python3
2+ # -*- coding: utf-8 -*-
3+
4+ class Dict (dict ):
5+ '''
6+ Simple dict but also support access as x.y style.
7+
8+ >>> d1 = Dict()
9+ >>> d1['x'] = 100
10+ >>> d1.x
11+ 100
12+ >>> d1.y = 200
13+ >>> d1['y']
14+ 200
15+ >>> d2 = Dict(a=1, b=2, c='3')
16+ >>> d2.c
17+ '3'
18+ >>> d2['empty']
19+ Traceback (most recent call last):
20+ ...
21+ KeyError: 'empty'
22+ >>> d2.empty
23+ Traceback (most recent call last):
24+ ...
25+ AttributeError: 'Dict' object has no attribute 'empty'
26+ '''
27+ def __init__ (self , ** kw ):
28+ super (Dict , self ).__init__ (** kw )
29+
30+ def __getattr__ (self , key ):
31+ try :
32+ return self [key ]
33+ except KeyError :
34+ raise AttributeError (r"'Dict' object has no attribute '%s'" % key )
35+
36+ def __setattr__ (self , key , value ):
37+ self [key ] = value
38+
39+ if __name__ == '__main__' :
40+ import doctest
41+ doctest .testmod ()
42+
You can’t perform that action at this time.
0 commit comments