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.
近期评论