Python Functions vs Methods [Key Differences]

The terms “function” and “method” are interchangeable in most programming languages. But there are differences. Let me explain this. In this tutorial, I will show you the key differences between Python functions vs methods.

Before understanding with examples, let me summarize the differences between Python functions and methods.

AspectFunctionMethod
DefinitionIndependent block of reusable code.Block of code associated with an object or class.
Syntaxdef function_name(parameters):def method_name(self, parameters):
CallingCalled by its name directly.Called on an object, with the object passed as the first parameter.
AssociationNot associated with any object or class.Defined within a class and operates on the data within the class.
UsageGeneral-purpose tasks.Manipulating the data of an object.
Examplepython\n def greet(name):\n return f"Hello, {name}!"\n print(greet("Alice"))\npython\n class Greeter:\n def __init__(self, name):\n self.name = name\n def greet(self):\n return f"Hello, {self.name}!"\n greeter = Greeter("Alice")\n print(greeter.greet())\n
Built-in Exampleslen(my_list)my_list.append(5)
Key DifferenceCan be called from anywhere in the code.Operates on the data contained within an instance of the class.

This table provides a quick reference for understanding the key differences between functions and methods in Python.

What is a Function in Python?

A function in Python is a block of reusable code designed to perform a specific task. It is defined using the def keyword, followed by the function name and parentheses containing any parameters. Functions can be called from anywhere in your code, making them highly versatile.

Syntax of a Function

Here is the syntax of a function in Python.

def function_name(parameters):
    # Function body
    return result

Example of a Function

Here is an example of a Python function.

def greet(name):
    return f"Hello, {name}!"

print(greet("Alice"))

In this example, the greet function takes a parameter name and returns a greeting message.

Here is the output you can see in the screenshot below:

Python Functions vs Methods

Check out Python Function Naming Conventions

What is a Method in Python?

A method is similar to a function but is associated with an object. Methods are defined within a class and operate on the data contained within that class. They are called on an instance of the class, and they implicitly pass the instance (self) as the first parameter.

Syntax of a Method

Here is the syntax of a method in Python.

class ClassName:
    def method_name(self, parameters):
        # Method body
        return result

Example of a Method

Here is an example of a method in Python.

class Greeter:
    def __init__(self, name):
        self.name = name
    
    def greet(self):
        return f"Hello, {self.name}!"

greeter = Greeter("Alice")
print(greeter.greet())

In this example, the greet method is defined within the Greeter class and operates on the instance variable name.

Here is the output in the screenshot below:

python function vs method

Key Differences Between Functions and Methods

  1. Association: Functions are independent blocks of code, while methods are tied to objects or classes.
  2. Calling: Functions are called by their name directly, whereas methods are called on an object and pass the object itself as the first parameter.
  3. Usage: Functions are used for general-purpose tasks, while methods are used to manipulate the data within an object.

Check out Python Function Examples with Parameters

Scenarios: When to Use Functions vs Methods in Python

Now, let me show you different scenarios, and you will learn when to use functions vs methods in Python with examples.

Scenario 1: General Utility Tasks

If you need to perform a task that doesn’t rely on the state of an object, a function is the way to go. For instance, a function to calculate the square of a number:

def square(number):
    return number ** 2

print(square(4))

Scenario 2: Object-Oriented Programming

When working with classes and objects, methods are essential. For example, if you’re modeling a bank account, you might use methods to deposit and withdraw money:

class BankAccount:
    def __init__(self, balance=0):
        self.balance = balance
    
    def deposit(self, amount):
        self.balance += amount
        return self.balance
    
    def withdraw(self, amount):
        if amount <= self.balance:
            self.balance -= amount
            return self.balance
        else:
            return "Insufficient funds"

account = BankAccount(100)
print(account.deposit(50))
print(account.withdraw(30))
print(account.withdraw(150))

In this scenario, the deposit and withdraw methods manipulate the balance attribute of the BankAccount class.

Scenario 3: Built-in Functions vs Methods

Python provides a plethora of built-in functions and methods. For example, the len() function is a built-in function:

my_list = [1, 2, 3, 4]
print(len(my_list))

In contrast, the append() method is a method of the list object:

my_list.append(5)
print(my_list)

Conclusion

Functions and methods are both fundamental components of Python programming. Functions can be called from anywhere in your code, making them ideal for general utility tasks. Conversely, methods are tied to objects and are used to manipulate the data within those objects. I hope now you understand the difference between function and method in Python.

You may also like:

Leave a Comment