Python迭代模式实例详解


本文摘自php中文网,作者小云云,侵删。

本文主要和大家分享Python迭代模式实例详解,主要以代码的形式和大家分享,希望能帮助到大家。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

# -*- 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()

运行结果:

1
2
a
b
c
45

以上就是Python迭代模式实例详解的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

Python 元类实例解析_Python

如何使用Python实现调查问卷的自动填写

Python之configparser配置文件详解

什么是Python popitem函数?示例解析

Python单例模式是什么

Python怎么粘贴代码

Python中(urlparse)模板的使用详解

Python怎么画直线

Python数据分析有什么用

怎么把字符串解析成浮点数或者整数

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...