2012-10-18 49 views
2

只傳遞一個參數。仍然我收到2個參數已被傳遞的錯誤。 headtail未被初始化爲-1。TypeError:enqueuqe需要1個位置參數,但通過了2個

class Queue_demo: 
    head=-1 
    tail=-1 
    a=[] 

    def enqueue(data=10): 
     if(head==-1 and tail==-1): 
      head=head+1 
      tail=tail+1 
      a.append(data) 
     else: 
      tail=tail+1 
      a.append(data) 

    def dequeue(): 
     y=a[head] 
     if(head==tail): 
      head,tail=-1,-1 
     else: 
      head=head+1 
     return y 

q1=Queue_demo() 
q2=Queue_demo() 
q1.enqueue(12) 

while(q1.tail==-1): 
    print(q1.dequeue()) 

回答

4

您的代碼有幾個問題。

直接導致你的錯誤的是你沒有給你的方法一個self參數。當您撥打q1.enqueue(12)時,Python會將其轉換爲Queue_demo.enqueue(q1, 12)。作爲第一個參數的方法被調用的對象被傳遞給方法。按照慣例,它通常被命名爲self

這導致我遇到第二個問題,一旦你通過了錯誤的錯誤數量的錯誤,你會遇到。您的實例將共享同一組數據成員,因爲它們當前正在訪問類變量headtaila,而不是實例變量。這會非常令人困惑,因爲向一個隊列添加一個項目會使其出現在所有其他隊列中。

要解決這個問題,你需要做的是在構造函數中創建這些變量(它只是一個名爲__init__的方法),而不是在類定義中定義它們。這裏就是你的__init__方法可能看上去像:

def __init__(self): 
    self.head = -1 
    self.tail = -1 
    self.a = [] 

記住,Python是經常從其他編程語言不同!你不需要聲明你的成員變量,只需開始在self上分配值作爲值,你就可以全部設置。

相關問題