Methods in Object-Oriented Programming in Python

Methods in Object-Oriented programming in Python: Before proceeding, I am assuming that you all guys are familiar with concepts of functions. If you are not familiar with functions then please follow the concept of function to understand functions. Functions and methods are very similar to each other. But also holds some differences. You will get to know after reading this full article.

python video tutorial

FunctionsFunctions are independent ie. they are not dependent on others. They can be called by their name itself.

Syntax
of function definition:

#Syntax of defining function

def function_name():
    pass

function_name()          #function_calling


Methods:
Functions and methods are used for the same purposes. But methods always belong to a class or object (OOPs Concept). They are always by an object. It has a “self” parameter by default. Methods are always defined inside the class. An object always refers to the “self” of a method to call method.

Syntax
of method definition:

#Syntax of defining method

class Test:
    def method_name(self):
        pass
    
obj = Test()
obj.method_name()

#Note: Methods are always defined inside the class.


Example 1
Program to find factorial of a number using function.

#Program to find factorial of a number

def fact(n):
    factorial = 1
    while(n>1):
        factorial = factorial*n
        n = n-1
    print("Factorial is: "+str(factorial))
        
fact(5)

Output:

#Output
#Factorial is: 120


Example 2:
Program to find factorial of a number using method.

#Program to find factorial of a number

class Test:
    def fact(self,n):
        factorial = 1
        while(n>1):
            factorial = factorial*n
            n = n-1
        print("Factorial is: "+str(factorial))

obj = Test()
obj.fact(5)

Output:

#Output
#Factorial is: 120