AttributeError:' str'对象没有属性' insert'

时间:2014-10-08 11:39:25

标签: python

我试图在我的链接列表中插入一段文字。但是,当我尝试这样做时,我得到一个错误" AttributeError:' str'对象没有属性' insert'"。我在python 3.3中写这个。

class Node:
def __init__(self, item= None , link= None ):
    self.item = item
    self.next = link

def __str__(self):
    return str(self.item)


class List:
def __init__(self):
    self.head = None
    self.count = 0

def is_empty(self):
    return self.count == 0

def is_full(self):
    return False

def reset(self):
    self.__init__()

def __len__(self):
    return self.count

def _getNode(self, index):
    node = self.head
    for _ in range(index):
        node = node.next
    return node

def insert(self, index, item):
    if index < 0:
        index = 0

    elif index > len(self):
        index = len(self)

    if index == 0:
        self.head = Node(item, self.head)
    else:
        node = self._getNode(index - 1)
        node.next = Node(item, node.next)

    self.count += 1

def delete(self, index):
    if self.is_empty():
        raise IndexError("List is empty")
    if index < 0 or index >= len(self):
        raise IndexError("Index is out of range")

    if index == 0:
        self.head = self.head.next
    else:
        node = self._getNode(index - 1)
        node.next = node.next.next

    self.count -= 1

import LinkedList
text= LinkedList.List()

def insert_num(line,text):
    text.insert(line - 1,text)

def delete_num(line):
    if line is None:
        text.reset
    else:
        text.delete(line)

def print_num(line):
    if line is None:
        i= 0
        while i< line.count:
            item= text._getNode(i)
            print (item)
    else:
        print(text._getNode(line))

while True:
    print("1. Insert")
    print("2. Delete")
    print("3. Print")
    print("4. Quit")
    command = int(input())
    if command == 1:
        line = int(input("At what line do you wish to insert your text?: "))
        text = input("Text: ")
        insert_num(line,text)
    elif command == 2:
        line = int(input("What line do you wish to delete?: "))
        delete_num(line)
    elif command == 3:
        line = int(input("What line do you wish to print?: "))
    elif command == 4:
        break
    else:
        print("invalid input, please select one of the following numbers:")

3 个答案:

答案 0 :(得分:0)

在主循环中,您拨打insert_num(line, text)。但是text这里是您在上面输入的文本字符串,而不是全局变量text,它是LinkedList类的一个实例。正如错误所说,字符串没有insert方法(因为它们是不可变的)。

答案 1 :(得分:0)

你称这两行

text = input("Text: ")
insert_num(line,text)

生成的text变量将是str类型,而不是链接列表。正如错误告诉你的那样,字符串没有insert

当你打电话给这两行时:

import LinkedList
text= LinkedList.List()

这是与text函数范围内存在的变量不同的insert_num变量。

答案 2 :(得分:0)

问题是变量范围。当您调用insert_num()过程时,您希望将新行(text参数,类型为str)插入LinkedList行,这也称为text但是因为该方法具有相同名称的参数,所以此(链接列表)不在范围内,因此该过程无法看到。

text= LinkedList.List()

def insert_num(line,text):
    text.insert(line - 1,text)

我重命名子程序的参数:

text= LinkedList.List()

def insert_num(line_number, new_line):
    text.insert(line_number - 1,new_line)