Python对象实例化

Cod*_*lus 2 python object instantiation

我是python的新手,需要一些实例化对象的帮助.python解释器在实例化我定义的类的对象时给了我麻烦.有两个班,BTNodeBST(其存储在文件中bst_node.pybst.py分别对应).

# 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
Run Code Online (Sandbox Code Playgroud)
# 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)
Run Code Online (Sandbox Code Playgroud)

所以,在翻译我做:

import bst as b
t1 = b.BST(8)
Run Code Online (Sandbox Code Playgroud)

我得到一个错误,说这个 constructor takes no arguments

构造函数显然是一个参数,value所以这里出了什么问题?我该如何解决这个错误?

谢谢,非常感谢所有帮助!

Mos*_*she 5

第一个问题是你调用了函数___init___而不是__init__.所有'特殊方法'都使用两个下划线.

此代码中的第二个问题是BTNode您重新定义__init__.你不能在python中重载函数.当你重新启动时,__init__你有效地删除了第一个构造函数.

第三个问题是你的用法is.is是一个运算符,检查两个对象是否完全相同并返回TrueFalse.在构造函数中,您有一些self.left is None正在检查self.left(尚未声明)的值,并检查它是否是None.要设置它,请使用=如下:self.left = None

要解决第二个和第三个问题,您应该使用默认参数值.例如:

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