Reputation: 61
I just started working with classes in Python and I am at a roadblock trying to print a binary tree that I created. Here is the code I have:
class Node(object):
def __init__(self, number):
self.number=number
self.right=None
self.lef=None
def add_node(self,number):
if number < self.number:
self.left = self.left.add_node(number)
if number > self.number:
self.right = self.right.add_node(number)
The first part represents the root of the tree and the add_node function adds a node in the tree. I created a new instance for the root of the tree:
Tree = Node(6)
The problem that I am facing is printing the tree. If I just say print Tree
, I get this:
<__main__.Node object at 0x10f6e5210>
Somebody told me that I have to create a function to actually print the tree and this function looks like the function that's creating a new node but so far I wasn't able to do that. Any help please?!
Upvotes: 1
Views: 2052
Reputation: 10985
You can add the __str__
method to determine how your node object reacts when used as a string, i.e. str(Node(6))
. This is useful if you want to give out a string representations in print statements etc. without calling methods directly.
class Node(object):
def __init__(self, number):
self.number=number
self.right=None
self.lef=None
def add_node(self,number):
if number < self.number:
self.left = self.left.add_node(number)
if number > self.number:
self.right = self.right.add_node(number)
def __str__(self):
return str(self.number)
print Node(6)
Edit:
While __str__()
returns bytes, __unicode__()
returns characters. __unicode__()
is actually supposed to replace __str__()
, so it's actually recommended to use __unicode__()
instead (in Python 2.x there's both for compatibility reasons).
A 3rd way to represent your object is __repr__()
which is used for less formal string representations but rather for debugging etc. The returned string should look like a valid Python expression that could be used to recreate an object with the same value.
For more information have a look at the language reference.
Upvotes: 1
Reputation: 52071
Yes you need to add a function to create a function to print
the value at the node. The function can be as simple as
def dis(self):
print(self.number)
And you can now print using
print (Tree.disp())
Upvotes: 0