ajknzhol
ajknzhol

Reputation: 6460

Object Oriented example in Python

I know its dumb question but i am trying to grasp the concepts of OOP in Python. Suppose i want to write the program for factorial in Procedural form, i would do something like this

def factorial(n):
    num = 1
    while n >= 1:
        num = num * n
        n = n - 1
    return num

f = factorial(3)
print f # 6

Now i want to rewrite the same factorial program in OO way. i am not getting how to write this same function using objects and classes.

class Factorial():
    def fact(n):
        num = 1
        while n >= 1:
            num = num * n
            n = n - 1
        return num

f = Factorial()
a = f.fact(3)
print a # TypeError: fact() takes exactly 1 argument (2 given)

I know this can be done more precisely in Functional way by using lambdas and other things, but i am learning the concepts of OOP. What i am doing wrong ?

Upvotes: 1

Views: 837

Answers (3)

STK
STK

Reputation: 162

I would also recommend these article for reading:

An Introduction to Object-Oriented Concepts in Python, Part 1

Unfortunately I cannot put more that 2 links But I'm sure you'll find other 4 parts of these.

Upvotes: 1

thefourtheye
thefourtheye

Reputation: 239573

When you are calling an instance method, by default the current object is passed as the first parameter to the function. In your case,

def fact(n):

when you call it like this

a = f.fact(3)

it will be actually treated like this

a = fact(f, 3)

The reason why the current object is passed is, to let the instance method make changes to the object. (Remember Python doesn't have any other keyword like this, like in some other languages).

But your function's signature doesn't match this (it expects only one parameter). That's why it is throwing

# TypeError: fact() takes exactly 1 argument (2 given)

To fix this, you have to change the signature to something like this

def fact(self, n):

Now, the self parameter will receive the current object being passed.

Upvotes: 3

Deelaka
Deelaka

Reputation: 13723

You forgot the self parameter:

class Factorial():
    def fact(self,n): #Forgot the self parameter huh?
        num = 1
        while n >= 1:
            num = num * n
            n = n - 1
        return num

I recommend you read these too:

Upvotes: 2

Related Questions