Python uses generators to implement iteratable objects. python generators

Source: Internet
Author: User

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.

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.