我對Python非常陌生,需要一些實例化對象的幫助。 python解釋器在實例化我定義的類的對象時給我帶來麻煩。有兩類,BTNode
和BST
(其分別存儲在文件中bst_node.py
和bst.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
那麼這裏出了什麼問題?我該如何解決這個錯誤?
謝謝,非常感謝所有幫助!
不是你的問題,但除非我錯了,你會因爲'is'進行比較,要麼是TRUE;或'FALSE'與像'self.left是none'行遇到了問題。改用'self.left = None'。 – askewchan 2013-03-18 20:57:33