回答編集履歴

1

追記

2021/09/15 12:07

投稿

can110
can110

スコア38266

test CHANGED
@@ -17,3 +17,159 @@
17
17
  listのサイズが0、すなわち`シーケンスが空`である場合は**即座に**ループは終了します。
18
18
 
19
19
  すなわちループ内の処理は実行されません。
20
+
21
+
22
+
23
+ # 追記
24
+
25
+
26
+
27
+ むしろ以下コードで示すような変態クラスも想定すると`len`なりでチェックする**べきではなく**
28
+
29
+ 単純に`for in`に任せた方がよいかもしれません。
30
+
31
+ 参考:[Pythonはどうやってlen関数で長さを手にいれているの?](https://www.slideshare.net/shimizukawa/how-does-python-get-the-length-with-the-len-function)
32
+
33
+
34
+
35
+ ```Python
36
+
37
+ class MyIterator:
38
+
39
+ def __init__(self,obj):
40
+
41
+ self.obj = obj
42
+
43
+ self.c = 0
44
+
45
+
46
+
47
+ # ここが変態
48
+
49
+ def __len__(self):
50
+
51
+ print('__len__')
52
+
53
+ return 0
54
+
55
+
56
+
57
+ def __next__(self):
58
+
59
+ print('__next__')
60
+
61
+ try:
62
+
63
+ r = self.obj[self.c]
64
+
65
+ self.c += 1
66
+
67
+ return r
68
+
69
+ except IndexError:
70
+
71
+ self.c = 0
72
+
73
+ raise StopIteration
74
+
75
+
76
+
77
+ def __iter__(self):
78
+
79
+ print('__iter__')
80
+
81
+ return self
82
+
83
+
84
+
85
+ def disp(it):
86
+
87
+ print('disp')
88
+
89
+ for e in it:
90
+
91
+ print(e)
92
+
93
+
94
+
95
+ for l in [[],[1,2]]:
96
+
97
+ print(l)
98
+
99
+ it = MyIterator(l)
100
+
101
+
102
+
103
+ print('just disp')
104
+
105
+ disp(it)
106
+
107
+
108
+
109
+ print('check len')
110
+
111
+ if len(it) > 0:
112
+
113
+ disp(it) # 呼ばれない
114
+
115
+
116
+
117
+ print('check if')
118
+
119
+ if it:
120
+
121
+ disp(it)# 呼ばれない
122
+
123
+
124
+
125
+
126
+
127
+ """
128
+
129
+ []
130
+
131
+ just disp
132
+
133
+ disp
134
+
135
+ __iter__
136
+
137
+ __next__
138
+
139
+ check len
140
+
141
+ __len__
142
+
143
+ check if
144
+
145
+ __len__
146
+
147
+ [1, 2]
148
+
149
+ just disp
150
+
151
+ disp
152
+
153
+ __iter__
154
+
155
+ __next__
156
+
157
+ 1
158
+
159
+ __next__
160
+
161
+ 2
162
+
163
+ __next__
164
+
165
+ check len
166
+
167
+ __len__
168
+
169
+ check if
170
+
171
+ __len__
172
+
173
+ """
174
+
175
+ ```