我正在测试我的Linked List的功能,截至目前我正在尝试使用我的getCount和getIndex函数。每次我尝试测试时都会出现此错误。
C:\Python33\python.exe "C:/Users/koopt_000/Desktop/College/Sophomore Semester 2/Computer Science 231/Chapter4/Test.py"
Traceback (most recent call last):
1
File "C:/Users/koopt_000/Desktop/College/Sophomore Semester 2/Computer Science 231/Chapter4/Test.py", line 28, in <module>
2
print(LinkedList.getCount(node1,101))
3
3
File "C:\Users\koopt_000\Desktop\College\Sophomore Semester 2\Computer Science 231\Chapter4\LinkedList.py", line 152, in getCount
2
if current.item == value:
1
3
AttributeError: 'int' object has no attribute 'item'
1
Process finished with exit code 1
我认为我的'节点1'被认为是一个int对象。这是我的getCount和getIndex的代码。
def getCount(self, value):
''' This function counts the amount of times a certain item is in the Linked List.'''
count = 0
current = self.item
while current is not None:
if current.item == value:
count += 1
current = current.link
return count
#--------------------------------------------------------------
def getIndex(self, value):
''' getIndex finds the index of the selected item and returns that value. '''
count = 0
current = self.head
while current is not None:
if current.item == value:
count += 1
current = current.link
return current.item1
这是我的代码,我正在测试getCount和getIndex函数。
from ListNode import ListNode
from LinkedList import LinkedList
node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node1.link = node2
node2.link = node3
def print_list(node):
while node:
print(node,)
node = node.link
print
def print_backward(list):
if list == None: return
head = list
tail = list.link
print_backward(tail)
print(head,)
print_list(node1)
print_backward(node1)
print(LinkedList.__max__(node1))
print(LinkedList.__min__(node1))
print(LinkedList.getCount(node1,2))
也许我正在使用getCount函数错误但是无论如何我改变了我的getCount函数和我的getIndex函数,所以它做了它应该做的事情?感谢
答案 0 :(得分:0)
你的这一行:
LinkedList.getCount(node1,2)
假设您将getCount称为类方法,而不是实例方法。但是,您将getCount定义为实例方法:
def getCount(self, value)
这可以在这个例子中得到证明:
class A:
def getCount(self, value):
print(self, value)
print(A.getCount(1,2)) # prints 1,2. So instead of self, you have 1.
所以在你的情况下,self被视为node1。这是违反直觉的,因为self应该引用对象的当前实例。 Meybe这是问题的一部分。使用您提供的代码段非常难以说清楚。