Get the App
SLTechnology News&Howtos  ›  Development  › 

How to implement iterator Protocol in yield in Python

Shulou Source: shulou.com Published: 2022-06-03 17:38:42 11月13日 Update

This article will explain in detail how to implement the iterator protocol in yield in Python. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

Description

1. Two ways for yield to implement iterator protocol: _ _ iter__ and next (Python 2) or _ _ next__ (Python 3).

2. Both methods make the object an iterator.

It can be type-checked collections using the Iterator abstract base class in the module.

Example

> def func (): Yield'I am'... Yield'a generatorships. > > type (func) # A function with yield is still a function > gen = func () > type (gen) # but it returns a generator > hasattr (gen,'_ iter__') # that's an iterableTrue > hasattr (gen) 'next') # and with. Next (. _ _ next__ in Python 3) True on "how to implement the iterator protocol in yield in Python" ends here Hope that the above content can be helpful to you, so that you can learn more knowledge, if you think the article is good, please share it for more people to see.

Tags: Iterations articles methods more good practical content examples objects articles modules knowledge types references help related check Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology NVidia Docker Apple macOS