Home  >  Article  >  Backend Development  >  Detailed explanation of Python iteration mode examples

Detailed explanation of Python iteration mode examples

小云云
小云云Original
2018-03-30 16:50:191502browse

This article mainly shares with you detailed examples of Python iteration mode, mainly in the form of code, hoping to help everyone.

# -*- coding: utf-8 -*-
"""
Created on Thu Mar 29 11:43:05 2018

@author: mz
"""

class Iterator(object):
    def Next(self):
        pass
    def HasNext(self):
        pass
    def First(self):
        pass
    
    def Forward(self):
        pass

class CocreteIterator(Iterator):
    def __init__(self, aggregate):
        self._aggregate = aggregate
    
    def Next(self):
        return self._aggregate.Next()
    
    def HasNext(self):
        return self._aggregate.HasNext()
    
    def First(self):
        return self._aggregate.First()
    
    def Forward(self):
        return self._aggregate.Forward()
    

class Aggregate(object):
    def CreateIterator(self):
        pass

    def Next(self):
        pass
    
    def HasNext(self):
        pass
    
    def First(self):
        pass
    
    def Attach(self, obj):
        pass
        
    def Forward(self):
        pass
 
    
class ConcreteAggregate(object):
    
    def __init__(self):
        self._lst = []
        self._index = 0
    
    def CreateIterator(self):
        return CocreteIterator(self)
    
    def Next(self):
        return self._lst[self._index]
    
    def HasNext(self):
        return self._index < len(self._lst)
    
    def First(self):
        self._index = 0
        return self._lst[0]
    
    def Attach(self, obj):
        self._lst.append(obj)
        
    def Forward(self):
        self._index += 1
        
    

if "__main__" == __name__:
    aggregate = ConcreteAggregate()
    
    aggregate.Attach(1)
    aggregate.Attach("2")
    aggregate.Attach("a")
    aggregate.Attach("b")
    aggregate.Attach("c")
    aggregate.Attach("45")
    
    it = aggregate.CreateIterator()
    
    while it.HasNext():
        print(it.Next())
        it.Forward()

Run result:

1
2
a
b
c
45

The above is the detailed content of Detailed explanation of Python iteration mode examples. 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