Python implements a method for implementing an iterative object with a generator

Source: Internet
Author: User
This article is mainly for you in detail how Python uses the generator to achieve the iterative object, has a certain reference value, interested in small partners can refer to, hope to help everyone.

Case Analysis:

A class of an iterative object that iterates over all the primes in a given range:

PN = Number (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?

The __iter__ method of the class is implemented into a generator function, and each yield returns a prime number


#!/usr/bin/python3class Number (object): Def __init__ (self, start, end):  Self.start = start  self.end = End    # Determine if a number is a prime def get_num (self, k):  if K >= 2:   for I in range (2, K):    if k% i = = 0:     return False   Retu RN True   def __iter__ (self):  for K in range (Self.start, self.end+1):   if Self.get_num (k):    # Is prime yield out    yield k     if __name__ = = ' __main__ ': num = number (2, +) for i in Num:  print (i)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.