我需要一些帮助为我的__iter__()
类编写UnorderedList()
方法。我试过这个:
def __iter__(self):
current = self
while current != None:
yield current
但循环并没有停止。以下是我的其他课程和代码:
class Node:
def __init__(self,initdata):
self.data = initdata
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self,newdata):
self.data = newdata
def setNext(self,newnext):
self.next = newnext
class UnorderedList:
def __init__(self):
self.head = None
self.count = 0
最佳答案
如果你想成功地迭代所有的项,你应该
def __iter__(self):
# Remember, self is our UnorderedList.
# In order to get to the first Node, we must do
current = self.head
# and then, until we have reached the end:
while current is not None:
yield current
# in order to get from one Node to the next one:
current = current.next
所以在每一步你都要更进一步。
顺便说一下,setter和getter在Python中不是以方法的形式使用的。如果需要,请使用属性,否则请将其全部忽略。
所以就这么做吧
class Node(object):
def __init__(self, initdata):
self.data = initdata
self.next = None
class UnorderedList(object):
def __init__(self):
self.head = None
self.count = 0
def __iter__(self):
current = self.head
while current is not None:
yield current
current = current.next