Difference between function and method in Python with example
Functions in Python
Function in Python refers to the block of statements that are intended to perform a specific task. To be specific, there are many Python functions that are used to perform a particular task.
For instance, print() is a function used to display the information on the output screen. Similarly, we have input(), for taking the user input. Such functions are known as built-in functions. In the same way, Python also provides the flexibility to created our own functions. These are known as user-defined functions.
Defining a function
Python allows us to define the function using def keyword. Let us see how function definition works :
def function_name(para1, para2, ...):
function statements
As mentioned, we use def keyword to define a function along with function name and parameters(if any).
Methods in Python
A Python class is a blueprint for creating objects. A Class may contain one or more function defined to perform a particular task. When a function is written inside a class, it is referred to as Method. This method is called using one of the following ways :
object_name.methodname()
class_name.methodname()
Example
# normal function fun1() defined using def keyword
def fun1():
print("I am a Function")
# Python Class
class Fun:
# fun2() is a method defined under class Fun
def fun2(self):
print("I am a Method")
# calling fun1() directly
fun1()
# making object of class
class_obj = Fun()
# calling method fun2() with class object
class_obj.fun2()
O/P :
I am a Function
I am a Method
That’s all about Difference between function and method in Python.