Skip to content

Commit 4f3b98f

Browse files
committed
add python_magic_methonds.py
1 parent e86a926 commit 4f3b98f

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,8 @@
3333
### python_thread_multiprocess.py: Python进阶: 聊聊IO密集型任务、计算密集型任务,以及多线程、多进程
3434

3535
### python_version36.py: Python3.6正式版要来了, 你期待哪些新特性?
36+
37+
### python_magic_methods: Python进阶: 实例讲解Python中的魔法函数(Magic Methods)
3638
===================================================================================================
3739

38-
### 您可以fork该项目,并在修改后提交Pull request
40+
### 您可以fork该项目, 并在修改后提交Pull request

python_magic_methods.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# _*_ coding: utf-8 _*_
2+
3+
"""
4+
python_magic_methods.py by xianhu
5+
"""
6+
7+
8+
# 定义一个能够自动比较大小的People类
9+
class People(object):
10+
11+
def __init__(self, name, age):
12+
self.name = name
13+
self.age = age
14+
return
15+
16+
def __str__(self):
17+
return self.name + ":" + str(self.age)
18+
19+
def __lt__(self, other):
20+
return self.name < other.name if self.name != other.name else self.age < other.age
21+
22+
print("\t".join([str(item) for item in sorted([People("abc", 18), People("abe", 19), People("abe", 12), People("abc", 17)])]))
23+
24+
25+
# Python实现任意深度的赋值 例如a[0] = 'value1'; a[1][2] = 'value2'; a[3][4][5] = 'value3'
26+
class MyDict(dict):
27+
28+
def __setitem__(self, key, value): # 该函数不做任何改动 这里只是为了输出
29+
print("setitem:", key, value, self)
30+
super().__setitem__(key, value)
31+
return
32+
33+
def __getitem__(self, item): # 主要技巧在该函数
34+
print("getitem:", item, self)
35+
# 基本思路: a[1][2]赋值时 需要先取出a[1] 然后给a[1]的[2]赋值
36+
if item not in self: # 如果a[1]不存在
37+
temp = MyDict() # 则需要新建一个dict
38+
super().__setitem__(item, temp) # 并使得a[1] = dict
39+
return temp # 返回a[1] 使得a[1][2] = value有效
40+
return super().__getitem__(item) # 如果a[1]存在 则直接返回a[1]
41+
42+
# 使用例子:
43+
test = MyDict()
44+
test[0] = 'test'
45+
test[1][2] = 'test1'
46+
test[3][4][5] = 'test2'

0 commit comments

Comments
 (0)