Here I have an attempt for implenenting a printable tree:
class Node(object):
def __init__(self, value, child=[]):
self.value = value
self.child = child
def __repr__(self):
print('Debug:', self.value)
valuestr = repr(self.value)
childstr = ', '.join([repr(x) for x in self.child])
return "Node({0}, [{1}])".format(valuestr, childstr)
def __str__(self):
return self.__repr__()
When I run the following code, it works as expected.
A=Node('A')
B=Node('B')
C=Node('C')
A.child=[B, C]
print(A)
# Output:
# Debug: A
# Debug: B
# Debug: C
# Node('A', [Node('B', []), Node('C' [])])
But, when A.child.append(B)
is used instead of A.child=[B, C]
, it causes an infinite recursion.
Debug: A
Debug: B
Debug: B
Debug: B
...
Debug: B
Traceback (most recent call last):
File "/storage/emulated/0/com.hipipal.qpyplus/scripts3/.last_tmp.py", line 22, in <module>
print(A)
File "/storage/emulated/0/com.hipipal.qpyplus/scripts3/.last_tmp.py", line 15, in __str__
return self.__repr__()
File "/storage/emulated/0/com.hipipal.qpyplus/scripts3/.last_tmp.py", line 12, in __repr__
childstr = ', '.join([repr(x) for x in self.child])
File "/storage/emulated/0/com.hipipal.qpyplus/scripts3/.last_tmp.py", line 12, in <listcomp>
childstr = ', '.join([repr(x) for x in self.child])
File "/storage/emulated/0/com.hipipal.qpyplus/scripts3/.last_tmp.py", line 12, in __repr__
childstr = ', '.join([repr(x) for x in self.child])
...
RuntimeError: maximum recursion depth exceeded while calling a Python object
And, in case of the following,
A=Node('A')
B=Node('B')
C=Node('C')
A.child.append(B)
print(C)
The same error occurs again; But with Debug: C
instead of Debug: A
in the first line.
What is causing this behaviour? Why is repr() acting strangely when nodes are appended to the list of children, not assigned?
Currently using Python 3.2.7, qpython for Android.