Sorry if this has been asked before, but I'm normally a java programmer and I'm trying to wrap my head around this whole self business in python. I understand that self is needed to differentiate class variables from instance variables, but what about functions? For example, I'm implementing a binaryTree class. Of course, there are simpler ways, but I'm trying to teach a student about classes, so that's why I went this route.
class Node:
def __init__(self,value):
self.left = None
self.right = None
self.value = value
class Tree:
def __init__(self):
self.root = None
def _insert(self, root, value):
if value < root.value:
if root.left == None:
root.left = Node(value)
else:
self._insert(root.left, value)
if value > root.value:
if root.right == None:
root.right = Node(value)
else:
_insert(root.right, value)
return
def insert(self, value):
if self.root == None:
self.root = Node(value)
else:
_insert(self.root, value)
As you can see, the binaryTree class has an insert() function to add a new node, it also has _insert() which basically acts as a private function. What I'm curious about is that the very last line of this snippet will give me an error: "NameError: name '_insert' is not defined", unless I call it as self._insert(self.root, value). Shouldn't the _insert() function work even if it's not called as part of the instance (i.e. using 'self')? I thought it would behave like a static method, so why is self needed for that function call? Why is the function required to be part of the instance?
thanks!