zoukankan      html  css  js  c++  java
  • 一个网友写的栈,问为啥不能迭代。具有__iter__ 和next方法的对象叫迭代器-七七巴巴黄页网

    一个网友写的栈,问为啥不能迭代。具有__iter__ 和next方法的对象叫迭代器-七七巴巴黄页网

    一个网友写的栈,问为啥不能迭代。具有__iter__ 和next方法的对象叫迭代器

    python视频培训班  


    class stack(object):
         
        def __init__(self):
            self.stack = []

        def push(self,str1):
            self.stack.append(str1)

        def pop(self):
            return self.stack.pop()

        def length(self):
            return len(self.stack)


    请问应该怎么遍历这个堆栈呢?
    请看迪艾姆公司python远程视频培训班黄哥的回答
    类只有实现了__iter__() 和next()方法(python3改为__next__()),生成的实例才能迭代
    具有__iter__ 和next方法的对象叫迭代器
    请看python2.7.5的代码
    #coding:utf-8
    """
    该代码由python远程培训班黄哥所写
    python远程培训http://www.qy7788.com.cn/shiyongxinxi/shiyongxinxi193.html
    qq:1465376564 tel:010-68165761
    """
    class stack(object):
        """只有实现了__iter__和next方法的类生成的实例才可以迭代"""
        def __init__(self):
            self.stack = []

        def push(self,str1):
            self.stack.append(str1)

        def pop(self):
            return self.stack.pop()

        def length(self):
            return len(self.stack)

        def __iter__(self):
            return self

        def __next__(self):
            try:
                return self.stack.pop()
            except IndexError:  
                raise StopIteration  

    s = stack()
    s.push("python远程培训")
    s.push("qq:1465376564 tel:010-68165761")
    s.push("python编程思路")
    for i in s:
        print i

    请看python3.3.2的代码
    #coding:utf-8
    """该代码由python远程培训班黄哥所写
    python远程培训http://www.qy7788.com.cn/shiyongxinxi/shiyongxinxi193.html
    qq:1465376564 tel:010-68165761  在python3.3.2环境下测试过 """
    class stack(object):
        """只有实现了__iter__和next方法的类生成的实例才可以迭代"""
        def __init__(self):
            self.stack = []
        def push(self,str1):
            self.stack.append(str1)
        def pop(self):
            return self.stack.pop()
        def length(self):
            return len(self.stack)
        def __iter__(self):
            return self
        def __next__(self):
            try:
                return self.stack.pop()
            except IndexError:  
                raise StopIteration  
    s = stack()
    s.push("python远程培训")
    s.push("qq:1465376564 tel:010-68165761")
    s.push("python编程思路")
    for item in s:
        print(item)

  • 相关阅读:
    Python编码和文件操作
    Python的list和tuple及dictionary
    Python代码对比
    python的基础知识
    day2 springcloud组件(nacos注册/配置中心 feign组件请求调用 gateway网关)
    springcloud与springboot版本对应关系
    git配置
    day1 分布式基础概念
    spring中的依赖注入(DI)笔记
    20210223 爱生气的书店老板(滑动窗口)
  • 原文地址:https://www.cnblogs.com/lexus/p/3342087.html
Copyright © 2011-2022 走看看