I am trying to write a recursive function within a class, but have some trouble using an object var as a method argument:
class nonsense(object):
def __init__(self, val):
self.val = val
def factorial(self, n=self.val):
if n<=1: return 1
return n*self.factorial(n=n-1)
The code above generates the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in nonsense
NameError: name 'self' is not defined
But if I don't refer to self.val, the error disappears, although having to specify n is redundant:
class nonsense(object):
def __init__(self, val):
self.val = val
def factorial(self, n):
if n<=1: return 1
return n*self.factorial(n=n-1)
What is the right way of doing this?