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)

  • 相关阅读:
    appium for windows 环境搭建
    jenkins+maven+testng参数化执行测试用例
    java追加文本到文件末尾
    jenkins下添加HTML Publisher Plugin及配置
    jenkins配置本机JDK和maven环境
    Linux运维基础入门(三):网络基础知识梳理03
    Linux运维入门(二):网络基础知识梳理02
    Linux运维基础入门(一)网络基础知识梳理01
    Linux实战教学笔记55:开源虚拟化KVM(三)管理虚拟网络
    Linux实战教学笔记54:开源虚拟化KVM(二)管理虚拟存储
  • 原文地址:https://www.cnblogs.com/lexus/p/3342087.html
Copyright © 2011-2022 走看看