Skip to content

Commit fa82a31

Browse files
committed
fix bugs in magic_method
1 parent ae2e1b0 commit fa82a31

File tree

1 file changed

+9
-12
lines changed

1 file changed

+9
-12
lines changed

python_magic_methods.py

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -22,29 +22,26 @@ 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[0][2] = 'value2'; a[0][2][3] = 'value3',构造出一颗多叉树类似结构
25+
# Python实现任意深度的赋值 例如a[0] = 'value1'; a[1][2] = 'value2'; a[3][4][5] = 'value3'
2626
class MyDict(dict):
27-
def __init__(self,name=''): # 增加初始化函数,将需要放置的value存储到内部中
28-
self.name=name
29-
def __str__(self): # 增加 __str__ 函数,将存储的元素输出出来
30-
return self.name
27+
3128
def __setitem__(self, key, value): # 该函数不做任何改动 这里只是为了输出
3229
print("setitem:", key, value, self)
33-
temp = MyDict(value)
34-
super(MyDict,self).__setitem__(key, temp)
30+
super().__setitem__(key, value)
3531
return
3632

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

4642
# 使用例子:
4743
test = MyDict()
4844
test[0] = 'test'
49-
test[0][2] = 'test1'
50-
test[0][2][5] = 'test2'
45+
test[1][2] = 'test1'
46+
test[3][4][5] = 'test2'
47+
print("==========================")

0 commit comments

Comments
 (0)