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'

3 Answers 3

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):
    ...
Sign up to request clarification or add additional context in comments.

2 Comments

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 :)
Sure; just Google "python subclass int."
1

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

def factorial(n,self)

to

def factorial(self, n)

Comments

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.

1 Comment

A terminology nit-pick: class methods 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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.