2014-07-06 108 views
-5

我正在學習Python中的類。運行兩個示例,兩個函數都有兩個參數(其中一個是給定的),但是,只有一個示例執行,但另一個不執行。class __init __()只需要2個參數(1給出)

儘管x.setdata()只有1個參數,但它仍會執行。 類的Firstclass: DEF使用setData(個體,值): self.data =值 高清顯示器(自): 打印(self.data)

#make two instances 
x=FirstClass() 
y=FirstClass() 

x.setdata("king arthur") #call methods: self is x?? 
y.setdata(3.31212) 

x.display() 
y.display() 

這一個不運行,錯誤msg: __init__() takes exactly 2 arguments (1 given)

class Heap: 

     def __init__(self, sorting_key): 
      """Initializes a new instance of a heap. 

      Args: 
       sorting_key: Specifies the attribute of the object inserted 
       into the heap, on the basis of which the heap was created. 
      """ 
      self.heap = list() 
      self.mapping = dict() 
      self.sorting_key = sorting_key 

     def heapify_up(self, child): 
       """Standard heapify operation, as described in CLRS. 
       Works by swapping the element originially at index child in the heap 
       with its parent until the heap property is satisfied. Modifies the 
       appropriate heap attribute 

       Args: 
        child: Index of the element that violates the heap property 

       Returns: 
        None 
       """ 
       parent = (child - 1)/2 
       # Swaps the element originally at the index child with its parent 
       # until the value of the specifed attribute of the parent is greater 
       # than the value of the specified attribute of the element itself 
       while (getattr(self.heap[parent], self.sorting_key) < 
         getattr(self.heap[child], self.sorting_key)): 
        if (parent == -1): 
         # This means child was 0, which means we have reached the 
         # top of the heap 
         return 

        # Swap the mappings as well to ensure that future references in 
        # the mapping dict refer to the correct position of the object in 
        # the heap 
        self.mapping[self.heap[parent].player] = child 
        self.mapping[self.heap[child].player] = parent 

        # Swap the parent and the child 
        temp = self.heap[parent] 
        self.heap[parent] = self.heap[child] 
        self.heap[child] = temp 

        # Move the child and parent pointers up the heap 
        child = parent 
        parent = (child - 1)/2 


    x=Heap() 
    x.__init__([42,32,54,1,3]) 

    x.heapify_up(l,5) 
    print x 
+2

「self is x?」 - 是的,'self'在該行中是'x'。這應該在每個Python'class'教程中解釋。 – BartoszKP

回答

4

這兩條線:

x=Heap() 
x.__init__([42,32,54,1,3]) 

應該是一個:

x=Heap([42,32,54,1,3]) 

請記住,當你做Heap()Heap.__init__被隱式調用。下面是一個演示:

>>> class Foo: 
...  def __init__(self): 
...   print("Foo.__init__ was called") 
... 
>>> Foo() 
Foo.__init__ was called 
<__main__.Foo object at 0x020AF030> 
>>> 
+0

謝謝!!是的,我明白,自己是X,但不知道如何打電話給班級。 – user3810193

+0

如果你介意幫助我,我有一個後續問題。 爲堆類 - 我試圖調用heapify_up函數。 (該函數將索引孩子最初的值與其父母進行比較,如果堆屬性被違反,則交換兩者),但獲得錯誤消息「列表索引超出範圍」。我打電話功能錯了嗎?謝謝! x =堆([8,4,6,5,7,3,2]) x.heapify_up(5)#違反堆屬性的子項的索引 print x.sorting_key – user3810193

相關問題