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?
As you have discovered, you cannot have
self.xxxin the header — rather have None and then correct in the body:The reason is that when the class object is being created there is no
self; besidesglobals(), the only names defined when Python gets tofactorialare__module__, and__init__.As an experiment to prove this to yourself, try this: