Python implements a method to implement iterable objects using generators

小云云
Release: 2018-03-29 14:17:31
Original
2115 people have browsed it

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)
Copy after login


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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!