File tree 3 files changed +65746
-0
lines changed
3 files changed +65746
-0
lines changed Original file line number Diff line number Diff line change
1
+ def begin ():
2
+ print ("装饰开始:瓜子板凳备好,坐等[生成]" )
3
+
4
+
5
+ def end ():
6
+ print ("装饰结束:瓜子嗑完了,板凳坐歪了,撤!" )
7
+
8
+
9
+ def wrapper_counter_generator (func ):
10
+ # 接受func的所有参数
11
+ def wrapper (* args , ** kwargs ):
12
+ # 处理前
13
+ begin ()
14
+ # 执行处理
15
+ result = func (* args , ** kwargs )
16
+ # 处理后
17
+ end ()
18
+ # 返回处理结果
19
+ return result
20
+ # 返回装饰的函数对象
21
+ return wrapper
22
+
23
+
24
+ class DIGCounter :
25
+ """
26
+ 装饰器-迭代器-生成器,一体化打包回家
27
+ """
28
+
29
+ def __init__ (self , start , end ):
30
+ self .start = start
31
+ self .end = end
32
+
33
+ def __iter__ (self ):
34
+ """
35
+ 迭代获取的当前元素
36
+ :rtype: object
37
+ """
38
+ return self
39
+
40
+ def __next__ (self ):
41
+ """
42
+ 迭代获取的当前元素的下一个元素
43
+ :rtype: object
44
+ :exception StopIteration
45
+ """
46
+ if self .start > self .end :
47
+ raise StopIteration
48
+ current = self .start
49
+ self .start += 1
50
+ return current
51
+
52
+ @wrapper_counter_generator
53
+ def counter_generator (self ):
54
+ """
55
+ 获取生成器
56
+ :rtype: generator
57
+ """
58
+ while self .start <= self .end :
59
+ yield self .start
60
+ self .start += 1
61
+
62
+
63
+ def main ():
64
+ """
65
+ 迭代器/生成器(iterator)是不可重复遍历的,
66
+ 而可迭代对象(iterable)是可以重复遍历的,
67
+ iter()内置方法只会返回不可重复遍历的迭代器
68
+ """
69
+
70
+ k_list = list (DIGCounter (1 , 19 ))
71
+ even_list = [e for e in k_list if not e % 2 == 0 ]
72
+ odd_list = [e for e in k_list if e % 2 == 0 ]
73
+ print (even_list )
74
+ print (odd_list )
75
+
76
+ g_list = DIGCounter (1 , 19 ).counter_generator ()
77
+ five_list = [e for e in g_list if e % 5 == 0 ]
78
+ print (five_list )
79
+
80
+
81
+ if __name__ == '__main__' :
82
+ main ()
You can’t perform that action at this time.
0 commit comments