Dies ist meine Implementierung einer Singly Linked List. Ich versuche, die benutzerdefinierte Implementierung des Druckverfahrens zu prüfen, indem mein eigenes Schreiben __repr__
__repr__ Implementierung in Linked List in Python
class SList:
def __init__(self):
self.root = None
self.size = 0
def insert(self, item):
if not item:
raise ValueError('Cannot add None item to a list')
self.size += 1
if self.root is None:
self.root = Node(item)
else:
p = Node(item)
p.next = self.root
self.root = p
"""Remove the element at the specific index"""
def remove(self, index):
if index < 0 or index >= self.size:
raise ValueError('Index cannot be negative or greater than the size of the list')
current = self.root
if index == 0:
self.root = self.root.next
else:
for _ in range(index - 1):
current = current.next
p = current.next.next
if p is not None:
current.next = p
else:
current.next = None
self.size -= 1
def __len__(self):
return self.size
def __repr__(self):
"[{}]".format(", ".join(map(str, self)))
def __iter__(self):
current = self.root
while current is not None:
yield current
current = current.next
class Node:
def __init__(self, data):
if data is None:
raise ValueError('Node cannot be instantiated without an item')
self.data = data
self.next = None
Dies ist, wo ich die Funktion aufrufen.
def main():
l = SList()
l.insert(12)
l.insert(11)
l.insert(2)
l.insert(21)
print(l)
Ich erhalte die folgenden Fehler
Traceback (most recent call last):
File "/Users/username/Dropbox/code/pydev/data_structures/app.py", line 12, in <module>
main()
File "/Users/usernamei/Dropbox/code/pydev/data_structures/app.py", line 9, in main
print(l)
TypeError: __str__ returned non-string (type NoneType)
aber ich klar bin eine formatierte Zeichenfolge aus der __repr__
Methode zurück. Ist meine Implementierung von __iter__
falsch? Was mache ich hier falsch?
Ich sehe nicht ein ' dorthin zurückkehren. – user2357112