我想知道哪个参数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但特别想了解一下这个例子。
不,它的原因......考虑这个......在你的代码中,你实际上(在找到正确的地方之后),将该节点添加到树中? – donkopotamus
正如您发布的链接所说,Python没有传递值或传递引用,只能传递对象。 – interjay
(不要使用'=='比较None,使用'is'(如'if x is None:...')) – donkopotamus