2013-03-18 117 views
2

我對Python非常陌生,需要一些實例化對象的幫助。 python解釋器在實例化我定義的類的對象時給我帶來麻煩。有兩類,BTNodeBST(其分別存儲在文件中bst_node.pybst.py):Python對象實例化

# file: bst_node.py 

class BTNode: 

    """a binary search tree node implementation""" 

    def ___init___(self, value): 
     self.value = value 
     self.left is None 
     self.right is None 
     self.parent is None 

    def ___init___(self, value, left, right, parent): 
     """set the parameters to corresponding class members""" 
     self.value = value 
     self.left = left 
     self.right = right 
     self.parent = parent 

    def is_leaf(self): 
     """check whether this node is a leaf""" 
     if self.left.value is None and self.right.value is None: 
      return True 
     return False 

# file: bst.py 

from bst_node import * 

class BST: 

    """a binary search tree implementation""" 
    def ___init___(self, value): 
     self.root = BTNode(value) 

    def insert(self, curRoot, newValue): 
     if curRoot.is_leaf(): 
      if newValue < curRoot.value: 
       newNode = BTNode(newValue, None, None, curRoot) 
       curRoot.left = newNode 
      else: 
       newNode = BTNode(newValue, None, None, curRoot) 
       curRoot.right = newNode 
     else: 
      if newValue < curRoot.value: 
       self.insert(curRoot.left, newValue) 
      else: 
       self.insert(curRoot.right, newValue) 

因此,在解釋我做的:

import bst as b 
t1 = b.BST(8) 

和我得到一個錯誤,說這個constructor takes no arguments

構造函數明確地帶有一個參數value那麼這裏出了什麼問題?我該如何解決這個錯誤?

謝謝,非常感謝所有幫助!

+2

不是你的問題,但除非我錯了,你會因爲'is'進行比較,要麼是TRUE;或'FALSE'與像'self.left是none'行遇到了問題。改用'self.left = None'。 – askewchan 2013-03-18 20:57:33

回答

4

除了強調數量的問題,您應該更換

def ___init___(self, value): 
    self.value = value 
    self.left is None 
    self.right is None 
    self.parent is None 

def ___init___(self, value, left, right, parent): 
    """set the parameters to corresponding class members""" 
    self.value = value 
    self.left = left 
    self.right = right 
    self.parent = parent 

def __init__(self, value, left=None, right=None, parent=None): 
    """set the parameters to corresponding class members""" 
    self.value = value 
    self.left = left 
    self.right = right 
    self.parent = parent 

因爲隨着@Moshe指出,你不能重載函數,你應該使用insted的默認參數。

2

___init___改爲__init__應該修復它。 (2個下劃線對3)

5

第一個問題是,你叫你的功能___init___而不是__init__。所有'特殊方法'使用兩個下劃線。

此代碼中的第二個問題是您在BTNode中重新定義了__init__。你不能在python中重載函數。當你reclare __init__你有效地刪除了第一個構造函數。

第三個問題是您使用isis是一個操作符,用於檢查兩個對象是否完全相同,並返回TrueFalse。在構造函數中,有幾個self.left is None正在檢查self.left(尚未聲明)的值,並檢查它是否爲None。要設置它,請按以下步驟使用=self.left = None

要解決第二和第三個問題,您應該使用default argument values。例如:

def __init__(self, value, left=None, right=None, parent=None):