Skip to content

Commit d1cc1fa

Browse files
committed
modify the magic method,extend the dict becomes a multi tree
1 parent 3c0ddf3 commit d1cc1fa

File tree

1 file changed

+12
-8
lines changed

1 file changed

+12
-8
lines changed

python_magic_methods.py

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -22,25 +22,29 @@ def __lt__(self, other):
2222
print("\t".join([str(item) for item in sorted([People("abc", 18), People("abe", 19), People("abe", 12), People("abc", 17)])]))
2323

2424

25-
# Python实现任意深度的赋值 例如a[0] = 'value1'; a[1][2] = 'value2'; a[3][4][5] = 'value3'
25+
# Python实现任意深度的赋值 例如a[0] = 'value1'; a[0][2] = 'value2'; a[0][2][3] = 'value3',构造出一颗多叉树类似结构
2626
class MyDict(dict):
27-
27+
def __init__(self,name=''): # 增加初始化函数,将需要放置的value存储到内部中
28+
self.name=name
29+
def __str__(self): # 增加 __str__ 函数,将存储的元素输出出来
30+
return self.name
2831
def __setitem__(self, key, value): # 该函数不做任何改动 这里只是为了输出
2932
print("setitem:", key, value, self)
30-
super().__setitem__(key, value)
33+
temp = MyDict(value)
34+
super(MyDict,self).__setitem__(key, temp)
3135
return
3236

3337
def __getitem__(self, item): # 主要技巧在该函数
3438
print("getitem:", item, self)
3539
# 基本思路: a[1][2]赋值时 需要先取出a[1] 然后给a[1]的[2]赋值
3640
if item not in self: # 如果a[1]不存在
37-
temp = MyDict() # 则需要新建一个dict
38-
super().__setitem__(item, temp) # 并使得a[1] = dict
41+
temp = MyDict(item) # 则需要新建一个dict
42+
super(MyDict,self).__setitem__(item, temp) # 并使得a[1] = dict
3943
return temp # 返回a[1] 使得a[1][2] = value有效
40-
return super().__getitem__(item) # 如果a[1]存在 则直接返回a[1]
44+
return super(MyDict,self).__getitem__(item) # 如果a[1]存在 则直接返回a[1]
4145

4246
# 使用例子:
4347
test = MyDict()
4448
test[0] = 'test'
45-
test[1][2] = 'test1'
46-
test[3][4][5] = 'test2'
49+
test[0][2] = 'test1'
50+
test[0][2][5] = 'test2'

0 commit comments

Comments
 (0)