一个网友写的栈,问为啥不能迭代。具有__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)

你可能感兴趣的:(ext)