Search⌘ K
AI Features

Functions vs. Methods

Understand the distinct roles of functions and methods in Python programming. Explore how methods are tied to classes and objects, while functions can exist independently, enhancing your coding clarity.

We'll cover the following...

A common misconception and source of confusion is that method and function are used interchangeably or as synonyms which is not at all correct. A method refers to a function that is part of a class and defined inside the body of the class. To access a method, we have to access an instance or object of the class using the ( . ) dot operator.

Method

Python:

Python 3.5
## define a class in Python
class addition:
## define a method inside a class
def sum(self, a, b):
return a+b
obj= addition() # Defining obj is object of addition class
print(obj.sum(2,3))

PowerShell:

Python 3.5
## define a class in PowerShell
class addition {
## define a method inside a class
[int[]] sum($a, $b){
return $a+$b
}
}
$obj = [addition]::new() #Defining obj is an object of addition class
Write-host($obj.sum(3,2))

Function

A function does not necessarily have to be defined in a class and can exist as a standalone function.

Methods are functions of the classes. This means that all methods are functions but not all functions are methods.

Python 3.8
## define a function
def add(a,b):
return a + b
result=add(2,3)
print(result)

Powershell:

C++
Function add($a,$b){
return $a + $b
}
$result= add 2 3
$result