Python uses generators to implement iteratable objects. python generators
The examples in this article share with you the specific code of using a generator to implement iteratable objects in python for your reference. The specific content is as follows:
Case Analysis:
Implement a class that can iterate objects. It can iterate all prime numbers within a given range:
Pn = Number (1, 30)
For k in pn:
Print (k)
Result :,.
How can this problem be solved?
Implement the _ iter _ method of the class into a generator function. Each time yield returns a prime number
#! /Usr/bin/python3 class Number (object): def _ init _ (self, start, end): self. start = start self. end = end # determine whether a number is a prime number def get_num (self, k): if k> = 2: for I in range (2, k ): if k % I = 0: return False return True def _ iter _ (self): for k in range (self. start, self. end + 1): if self. get_num (k): # The prime Number yield goes out yield k if _ name _ = '_ main _': num = Number (2, 30) for I in num: print (I)
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.