magic methods 7

BIF : iter()、next()

We can use this two BIF to realize the function of for statement.

1
2
3
4
5
6
7
8
9
>>> for each in "ABCDE":
print(each)


A
B
C
D
E

The before with for can be realized with the two BIF and while statement in below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
>>> string = "ABCDE"
>>> it = iter(string)
>>> while True:
try:
each = next(it)
except StopIteration:
break
print(each)


A
B
C
D
E

The magic methods of two BIF is __iter__() and __next__(). The returned value of the former is itself while the latter dominates the rule of the iteration.

Try with Fibonacci sequence.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Fibs:
def __init__(self):
self.a = 0
self.b = 1
def __iter__(self):
return self
def __next__(self):
self.a, self.b = self.b, self.a + self.b
return self.a
# Pay attention to the limit!
>>> fibs = Fibs()
>>> for each in fibs:
if each < 1000:
print(each)
else:
break


1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987

We can add a parameter to control the iteration.

1
2
3
4
5
6
7
8
9
10
11
12
class Fibs:
def __init__(self, n=10):
self.a = 0
self.b = 1
self.n = n
def __iter__(self):
return self
def __next__(self):
self.a, self.b = self.b, self.a + self.b
if self.a > self.n
raise StopIteration
return self.a