Skip to content

Commit 7f5a625

Browse files
committed
add doctest sample
1 parent 1234f0f commit 7f5a625

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

samples/debug/mydict2.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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+

0 commit comments

Comments
 (0)