我有以下代碼:class Node: def __init__(self,data): self.data = data self.next = Noneclass linkedList: def __init__(self): self.top = None def isempty(self): return self.top== None def push(self,data): new_node = Node(data) #if self.top ==None: # self.top= new_node # return new_node.next = self.top self.top = new_node def pop(self): if self.top ==None: print('underflow comdition') return temp = self.top self.top = self.top.next return temp.data def top(self): if self.isempty(): print('empty stack') return return self.top.data def printstack(self): if self.isempty(): return temp = self.top print('stack from top') while temp != None: print(temp.data) temp = temp.nextllist = linkedList()llist.push(5)llist.push(7)llist.push(9)llist.push(11)llist.push(13)llist.push(15)llist.push(17)llist.pop()llist.pop()llist.top()llist.pop()llist.push('oolala')llist.printstack()但我收到以下錯誤:TypeError Traceback (most recent call last)<ipython-input-16-a71ab451bb35> in <module> 47 llist.pop() 48 llist.pop()---> 49 llist.top() 50 llist.pop() 51 llist.push('oolala')TypeError: 'Node' object is not callable我該如何解決?
1 回答

臨摹微笑
TA貢獻(xiàn)1982條經(jīng)驗 獲得超2個贊
您覆蓋了屬性top:它不能既是變量又是方法。
首先,您將其定義為方法:
def top(self):
...
但是,稍后,您使用top節(jié)點屬性覆蓋它:
self.top = new_node
top現(xiàn)在是 a Node,你不能調(diào)用節(jié)點。
我建議您更改方法名稱;作為一般做法,方法應(yīng)該是動詞,就像您使用pushand所做的那樣pop。
def show_top(self):
if self.isempty():
print('empty stack')
return
return self.top.data
...
llist.pop()
llist.show_top()
llist.pop()
llist.push('oolala')
llist.printstack()
添加回答
舉報
0/150
提交
取消