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中%r和%s的用法区别

Python如何求阶乘

windows下Python安装paramiko模块和pycrypto模块

Python里int什么意思

Python语言的特点是什么

怎么看Python是否安装成功?

Python smtp发送邮件的详细介绍(附代码)

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




打赏

取消

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

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

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

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

评论

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