0

Not sure what is wrong with the Python code below. Will appreciate any help. I have looked into here and here, but could not solve my issue.

Code:

class myClass:
    def factorial(n,self):
        if n == 1:
            return 1
        else:
            return n * self.factorial(n-1)

obj = myClass()
obj.factorial(3)            

Error

Traceback (most recent call last):
      File "a.py", line 9, in <module>
        obj.factorial(3)
      File "a.py", line 6, in factorial
        return n * self.factorial(n-1)
    AttributeError: 'int' object has no attribute 'factorial'
Community
  • 1
  • 1
matuda
  • 195
  • 2
  • 16

3 Answers3

3

You transposed the parameter names for factorial. The one that refers to the object itself must come first. As it is, you're trying to access the factorial variable of the number that was passed in. Change your definition of factorial to this:

def factorial(self, n):
    ...
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
  • although this is another question, but is there a possibility to extend int class the way you show? for a class, say `MyIntClass` - how can we instantiate it? with other data structures (hashes, arrays, strings) it's pretty easy (and there are several examples on SO) but can't say the same for int. at least for me :) – marmeladze Oct 09 '15 at 22:49
  • Sure; just Google "python subclass int." – TigerhawkT3 Oct 09 '15 at 22:51
1

self needs to be the first argument to a class function. Change

def factorial(n,self)

to

def factorial(self, n)
BlivetWidget
  • 10,543
  • 1
  • 14
  • 23
1

change your method signature to

def factorial(self, n)

instead of

def factorial(n, self)

because when you call a class method via object. python expects reference to the class object as a first parameter. in your case it's 'int'. which is not reference to the class object.

Asav Patel
  • 1,113
  • 1
  • 7
  • 25
  • A terminology nit-pick: [class methods](https://docs.python.org/3/library/functions.html#classmethod) in Python are actually quite different from typical "object" methods (and from most other languages' "class methods", which are usually more like Python's [static methods](https://docs.python.org/3/library/functions.html#staticmethod)). – Kevin J. Chase Oct 09 '15 at 23:48