AttributeError:'str'对象没有属性'插入'
我试图插入一段文字到我的链表中。然而,当我尝试做到这一点时,我得到一个错误“AttributeError:'str'object has no attribute'insert'”。我在Python 3.3中写这个。AttributeError:'str'对象没有属性'插入'
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:")
在您的主循环中,您可以拨打insert_num(line, text)
。但是text
这里是你输入的文本字符串,而不是全局变量text
,它是你的LinkedList类的一个实例。如错误所述,字符串没有插入方法(因为它们是不可变的)。
谢谢,发现错误! – Sean 2014-10-08 11:48:23
@Sean如果您发现答案有帮助,请点击复选标记以接受答案。 – 2014-10-08 13:06:54
你叫这两条线
text = input("Text: ")
insert_num(line,text)
产生的text
变量是str
类型,而不是一个链表。字符串没有insert
,正如错误告诉你的那样。
而当你把这些两行:
import LinkedList
text= LinkedList.List()
这比你insert_num
函数的范围内存在的一个不同text
变量。
问题是变量作用域。当您打电话给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)
不要写“诗抱歉的代码墙”,归结代码为[小例子(https://开头stackoverflow.com/help/mcve)_before asking_! – l4mpi 2014-10-08 11:51:17
请不要编辑提问他们回答的问题。相反,接受一个答案。 – geoffspear 2014-10-08 12:35:40