[Tutor] Understanding Object oriented programming with Python

Manprit Singh manpritsinghece at gmail.com
Fri Sep 4 15:17:20 EDT 2020


Dear sir ,

Please consider a problem of finding the factorial of a number, i have to
solve this problem using OOPS concepts . I just want to check the
understanding of my concepts through this program, which is written below .

class factorial:                      # Defining class factorial
    def __init__(self):             # Initializer
        self.num = None          # Initial value of the number
        self.fact = None           # Initial value of factorial of the
number

    def setnum(self, x):          # Setter , to set the value of self.num
        self.num = x

    def factcalc(self):             # Method that will calculate the
factorial
        if self.num in {0,1}:
            self.fact = 1
        else:
            start = 1
            for i in range(2, self.num + 1):
                start = start * i
            self.fact = start

    def getfact(self):               # Method that will return the factorial
        self.factcalc()
        return self.fact


fac = factorial()                    # Creating new instance of class and
assign this object to a variable fac
fac.setnum(3)                     # passing argument to setter(Argument is
the number whose factorial has to be found)
print(fac.getfact())              # This will return the factorial of the
number passed to setter, which is 3

The output is 6

Just need to know, if my understanding of basic concept is right or not.
This problem can be improved further using OOPS ?

Regards
Manprit Singh


More information about the Tutor mailing list