Sitemap

Functions vs Methods

As I continue learning Python, I’m using these study notes to summarise key concepts I come across. Today’s focus is on functions vs. methods — two fundamental concepts in Python programming.

Press enter or click to view image in full size
Image by jcomp on Freepik

What is a Function?

A function is a reusable block of code that performs a specific task. It is independent and can be called anywhere in the program.

Example of a Function:

def add_numbers(a, b):  
return a + b

result = add_numbers(5, 10)
print(result) # Output: 15

What is a Method?

A method is a function that is associated with an object and belongs to a class. It typically operates on data stored in the object.

Get Jenny Core-Holt’s stories in your inbox

Join Medium for free to get updates from this writer.

Example of a Method:

class Calculator:  
def add(self, a, b):
return a + b

calc = Calculator()
result = calc.add(5, 10)
print(result) # Output: 15

🔹 Here, add() is a method because it belongs to the Calculator class and must be called using an instance (calc).

What are the Key Differences?

Press enter or click to view image in full size

Example of Both Function and Method:

# Function (independent)
def greet(name):
return "Hello, {name}!"

print(greet("Alice")) # Output: Hello, Alice!

# Method (inside a class)
class Person:
def __init__(self, name):
self.name = name

def greet(self): # Method
return "Hello, {self.name}!"

p = Person("Bob")
print(p.greet()) # Output: Hello, Bob!

🔹 greet(name) is a function because it is independent.
🔹 greet() inside Person class is a method because it belongs to an object (p).

Conclusion

Functions are standalone, while methods belong to objects and typically modify or interact with an object’s data. Both are powerful tools that help make Python code reusable and structured.

Written by Jenny Core-Holt

Frontend Designer and Developer on the journey to becoming a Data Analyst. Avid tea drinker and stand up paddle boarder, having a dabble in snowboarding.