_thonpr__在python中的链接列表中实现

时间:2016-12-20 16:52:57

标签: python

这是我对单链表的实现。我正在尝试编写自己的__repr__

来测试print方法的自定义实现
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

这是我调用该函数的地方。

def main():
   l = SList()
   l.insert(12)
   l.insert(11)
   l.insert(2)
   l.insert(21)
   print(l)

我收到以下错误

 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)

但是我明显从__repr__方法返回格式化字符串。我__iter__的实现是否错误?我在这里做错了什么?

2 个答案:

答案 0 :(得分:2)

您错过了return声明。将其更改为:

def __repr__(self):
    return "[{}]".format(", ".join(map(str, self)))

如果您没有明确提及,python会将返回视为None

答案 1 :(得分:1)

您正试图为str对象调用Node没有它的对象(可能是None,但不会有问题,因为{{1已实施None

str实施__str__(在Node类中添加此行):

Node

另外,添加def __str__ (self): return str(self.data) (函数默认返回return):

None