Learn Tree Traversal by Building a Binary Search Tree - Step 13

Tell us what’s happening:

I already know what the answer is, but I do not understand the syntax. From what I could gather, by returning TreeNode(key), the init method of the TreeNode class will run using “node” as the “self” parameter. Why is “node” the “self” parameter that the init method uses? Apologies in advance if this is the wrong place to submit this question!

Your code so far

class TreeNode:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None

class BinarySearchTree:
    def __init__(self):
        self.root = None

    def insert(self,key):
        self.root = self._insert(self.root, key)


# User Editable Region

    def _insert(self, node, key):
        pass

# User Editable Region

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36

Challenge Information:

Learn Tree Traversal by Building a Binary Search Tree - Step 13

I’m not sure I understand your question. Could you try to phrase it differently?

class TreeNode:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None

The first parameter of the method in class is always the class instance. The self is used as a convention it could be named anything.

Definitely, and thank you for being willing to help! So in the solution to this step, I have to return TreeNode(key). To my understanding, this will run the init method in the TreeNode class. The init method needs two parameters: key (which I provide in my return call) and self. I know ‘self’ is never explicitly called, but instead like you pointed out, self is the instance. My question is: what is the instance that is being called here?

Im used to the instance appearing in a line like “instance.class-method(p1, p2, etc.)”, so I’m just confused on what instance is being passed into TreeNode’s init method when the return line is called.

That’s a really good question.

__init__ is often misnamed as constructor, but in fact, as the name suggests it only initializes the new instance.

When TreeNode(key) is called, two things happen:

  • TreeNode.__new__(key) is called to actually create the new instance. It’s a class method, so it takes as first parameter, the class itself. It’s way rarer to write custom __new__ method when defining class, but there are some uses when that might be needed.
  • Then it’s passed to the __init__, instance method, as first argument.

Ahhh ok, interesting.That helps a ton, I’ll definitely be looking into how the new method works. Thank you!