I am new to programming and am trying to calculate the depth of a binary tree in Python . I believe that my error is because depth is a method of the Node class and not a regular function. I am trying to learn OOP and was hoping to use a method. This might be a newbie error... Here is my code:
class Node:
def __init__(self, item, left=None, right=None):
"""(Node, object, Node, Node) -> NoneType
Initialize this node to store item and have children left and right.
"""
self.item = item
self.left = left
self.right = right
def depth(self):
if self.left == None and self.right == None:
return 1
return max(depth(self.left), depth(self.right)) + 1
i receive this error:
>>>b = Node(100)
>>>b.depth()
1
>>>a = Node(1, Node(2), Node(3))
>>>a.depth()
Traceback (most recent call last):
File "C:\Program Files\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 1, in <module>
# Used internally for debug sandbox under external interpreter
File "C:\Program Files\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 15, in depth
builtins.NameError: global name 'depth' is not defined
new beeis spellednewbie, if I'm not mistaken.depth()as a method solves the problem), but somewhat incomplete. The root cause that explains why you can't access the method from inside itself but you can with a regular function is a somewhat involved detail of how scope and class definition works in Python. When you call a regular module-level function, it's "global" scope will be the module it's defined in, which contains this function. However, the scope where methods are defined can be considered to be discarded after the type object created.self.left is None, notself.left == None, as PEP 8 says. This protects you from badly-designed classes, and adds a performance boost, but the real reason is that "is None" stands out as the one Pythonic way to do it, and makes your code more readable to experienced Python coders.