关于Python类对象如何实现的反向迭代

来源:互联网 发布:http端口号是多少 编辑:程序博客网 时间:2024/06/05 05:42
#!/bin/python#python对象实现反向迭代有两个前提的,首先对象队列的大小是确定的,或者实现了__reversed__()方法.
一般做法是类模板分配一个id属性
class Node:    def __init__(self,value):        self._id=value        self._child=[]    def __repr__(self):        return 'Node({!r})'.format(self._id)    def __iter__(self):        return iter(self._child)    def reversed(self,id):        while n>0:            yield self._child[n]            n-=1    def add_child(self,node):        self._child.append(node)    def depth_first(self):        yield self        for c in self:            yield from c.depth_first()
原创粉丝点击