I want to show everything that is connected to specific node with print function but so far I can't avoid using global to do so. How can I make my __repr__function cleaner and more local? Whole code that I got so far below:
current_parent = None
indent_increase = 1
class Node(object):
def __init__(self, data):
self.data = data
self.parent = None
self.children = []
def add_child(self, obj):
self.children.append(obj)
obj.parent = self.data
def __repr__(self):
global current_parent
global indent_increase
if self.children:
print_data = ""
print_data += "Node " + str(self.data) + " ↴" + "\n"
indent = " "
for child in self.children:
if current_parent != child.parent:
current_parent = child.parent
indent_increase += 1
print_data += ((indent * indent_increase) + str(child) + "\n")
else:
print_data += ((indent * indent_increase) + str(child) + "\n")
indent_increase = 1
current_parent = 0
return print_data
else:
return "Node " + str(self.data)
a = Node(1)
b = Node(2)
c = Node(3)
d = Node(4)
e = Node(5)
c.add_child(d)
a.add_child(b)
a.add_child(c)
a.add_child(e)
print(a)
Desired output:
Node 1 ↴
Node 2
Node 3 ↴
Node 4
Node 5
You can work without globals
- you just need to split the result from nested nodes into lines and indent each of them before returning the result:
class Node(object):
def __init__(self, data):
self.data = data
self.parent = None
self.children = []
def add_child(self, obj):
self.children.append(obj)
obj.parent = self
def __repr__(self):
if self.children:
print_data = "Node " + repr(self.data) + " ↴" + "\n"
indent = " "
for child in self.children:
for line in repr(child).splitlines():
print_data += indent + line + "\n"
return print_data
else:
return "Node " + repr(self.data)
I made an example with more nested Nodes at https://repl.it/repls/ZanyKlutzyBase