如果这个问题放错地方或重复,我预先表示歉意。
这个问题本质上与双重链表迭代器python类似。
但是,与引用的问题不同,我不希望创建一个包含大量元数据并提供迭代器的总体链表对象(它们对于我的应用程序不是必需的)。
我的问题是:是否有根本的原因,为什么我不应该或者不能提供一个迭代器,该迭代器不对包含的元素进行迭代,而是跳过通过引用相互链接的不同元素对象?
迭代器对于代码的正常运行不是必需的,但是我更喜欢for item in构造的语法糖。
我的实现看起来像这样(简化版):
class LinkedAccount:
def __init__(self, someParameter, nextAccount = None, prevAccount = None):
self.someParameter = someParameter
self.next = nextAccount
self.prev = prevAccount
if nextAccount is not None:
self._tell_next()
if prevAccount is not None:
self._tell_prev()
def _tell_next(self):
if self.next is not None:
self.next._recv_next(self)
def _recv_next(self,prevAccount):
self.prev = prevAccount
def _tell_prev(self):
if self.prev is not None:
self.prev._recv_prev(self)
def _recv_prev(self,nextAccount):
self.next = nextAccount
def __iter__(self):
return AccountIterator(self)
class AccountIterator:
def __init__(self,Account):
self.Account = …Run Code Online (Sandbox Code Playgroud)