Python对象实例化

时间:2013-03-18 20:52:03

标签: 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

# 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所以这里出了什么问题?我该如何解决这个错误?

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

3 个答案:

答案 0 :(得分:5)

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

此代码中的第二个问题是BTNode您重新定义了__init__。你不能在python中重载函数。当您重新发送__init__时,您实际上删除了第一个构造函数。

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

要解决第二个和第三个问题,您应该使用default argument values。例如:

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

答案 1 :(得分: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 :(得分:2)

___init___更改为__init__应该可以解决问题。 (2次强调与3次)