I am trying to implement a recursive function within a class declaration in Python. However, the function doesn't seem to accept parameters. If I declare a recursive function outside the Class, it works.
[A while loop][1] will also do the trick. (See "Traversing values). I've banged my head on the keyboard enough to permit an SO post, IMHO.
class Node:
def __init__(self, value):
self.data = value
self.next = None
def traverse(self, node):
print(node.data)
if (node.next == None):
return
else:
node.traverse(node.next)
>>> a = Node('a')
>>> b = Node('b')
>>> c = Node('c')
>>> a.next = b
>>> b.next = c
>>> Node.traverse(a)
Traceback (most recent call last):
File "<pyshell#62>", line 1, in <module>
Node.traverse(a)
TypeError: traverse() missing 1 required positional argument: 'node'
[1]: https://medium.com/@kojinoshiba/data-structures-in-python-series-1-linked-lists-d9f848537b4d
selfas the first argument.a.traverse()methods are meant to be called on the instance. This really has nothing to do with recursion