Brady Sheehan Brady Sheehan - 1 year ago 74
Python Question

Are these arguments in Python being passed by value or by reference?

I am wondering which of the arguments in the call

self._insertInteral(value, self.root.rightChild)
are by value and which are by reference? I am still learning Python and was reading about the pass by object methodology in Python. I think my misunderstanding on the topic may be the reason why my function for inserting into a binary tree does not result in the value being inserted.

Here is my code:

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)
if root.value > value:
self._insertInternal(value, root.leftChild)
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)
elif self.root.value > value:
print str(self.root.value) + '>' + str(value)
self._insertInternal(value, self.root.leftChild)
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


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

I did checkout this post Understanding Python's call-by-object style of passing function arguments but was wondering about this example specifically.

Answer Source

Python is pass by assignment. Within your BinaryTree._insertInternal the assignment of root argument (also the local variable within the scobe of that method) is initially assigned the value of the root node (in this case, the value is an object reference), and the statement root = Node(None, None, value) is a new assignment, thus it becomes different to the initially passed in thus different to the instance's self.root.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download