Home  >  Article  >  Backend Development  >  Python implements a method to implement iterable objects using generators

Python implements a method to implement iterable objects using generators

小云云
小云云Original
2018-03-29 14:17:312031browse

This article mainly introduces in detail how python uses generators to implement iterable objects. It has certain reference value. Interested friends can refer to it. I hope it can help everyone.

Case analysis:                                                                                                                                                                                                                                (1, 30)

for k in pn:

print(k)

The result is: 2,3,5,7,11,13,17,19 ,23,29

How to solve this problem?

Implement the __iter__ method of this class into a generator function, and return a prime number each time yield

#!/usr/bin/python3
class Number(object):
 def __init__(self, start, end):
  self.start = start
  self.end = end
   
 # 判断一个数字是否是素数
 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):
    # 是素数yield出去
    yield k
     
if __name__ == '__main__':
 num = Number(2, 30)
 for i in num:
  print(i)


The above is the detailed content of Python implements a method to implement iterable objects using generators. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn