2016-05-24 67 views
0

我想知道哪个参数self._insertInteral(value, self.root.rightChild)是根据价值和哪些参考?我仍然在学习Python,并在Python中阅读关于通过对象方法学的知识。我认为我对这个主题的误解可能是为什么我的函数插入二叉树不会导致插入的值。Python中的这些参数是通过值还是通过引用传递的?

这里是我的代码:

class Node: 
    def __init__(self, leftChild, rightChild, value): 
     self.leftChild = leftChild 
     self.rightChild = rightChild 
     self.value = value 

class BinaryTree: 
    def __init__(self, root): 
     self.root = root 
    def _insertInternal(self, value, root): 
     if root is None: 
      root = Node(None, None, value) 
      print 'new node, root.value = ' + str(root.value) 
      return 
     if root.value > value: 
      self._insertInternal(value, root.leftChild) 
     else: 
      self._insertInternal(value, root.rightChild) 

    def insert(self, value): 
     print 'attempting to insert value = ' + str(value) 
     if self.root is None: 
      self.root = Node(None, None, value) 
      return 
     elif self.root.value > value: 
      print str(self.root.value) + '>' + str(value) 
      self._insertInternal(value, self.root.leftChild) 
     else: 
      print str(self.root.value) + '<' + str(value) 
      self._insertInternal(value, self.root.rightChild) 


if __name__ == '__main__': 
    root = Node(None, None, 10) 
    tree = BinaryTree(root) 
    print tree.root.leftChild 
    print tree.root.rightChild 
    print tree.root.value 


    tree.insert(5) 

    print tree.root.leftChild 
    print tree.root.rightChild 
    print tree.root.value 

我做了结帐这个帖子Understanding Python's call-by-object style of passing function arguments但特别想了解一下这个例子。

+1

不,它的原因......考虑这个......在你的代码中,你实际上(在找到正确的地方之后),将该节点添加到树中? – donkopotamus

+1

正如您发布的链接所说,Python没有传递值或传递引用,只能传递对象。 – interjay

+1

(不要使用'=='比较None,使用'is'(如'if x is None:...')) – donkopotamus

回答

2

Python是pass by assignment。在BinaryTree._insertInternal之内,root参数的分配(也是该方法的scobe内的局部变量)最初被分配了根节点的值(在这种情况下,该值是对象引用),并且语句root = Node(None, None, value)是一个新的分配,因此它变得与最初通过的不同,因此与实例的self.root不同。

+0

感谢您的链接。我想我明白现在发生了什么。 –

相关问题