What is the difference between a method and a function?

Overview

A function is a set of instructions or procedures to perform a specific task, and a method is a set of instructions that are associated with an object.

A function is used to split the code into easily understandable parts, which can be reused as well.

Differences

Some differences between a function and method are listed below:

  • A function doesn’t need any object and is independent, while the method is a function, which is linked with any object.

  • We can directly call the function with its name, while the method is called by the object’s name.

  • Function is used to pass or return the data, while the method operates the data in a class.

  • Function is an independent functionality, while the method lies under object-oriented programming.

  • In functions, we don’t need to declare the class, while to use methods we need to declare the class.

  • Functions can only work with the provided data, while methods can access all the data provided in the given class.

Now, explore it further in the next section with a coding example.

Coding example

Click the "Run" button to execute the below example.

# Function example
def greet_function(name):
return "Hello, {}!".format(name)
# Method example
class Greeter:
def __init__(self, name):
self.name = name
def greet_method(self):
return "Hello, {}!".format(self.name)
# Using the function
print(greet_function("Alice")) # Output: Hello, Alice!
# Using the method
greeter_object = Greeter("Bob")
print(greeter_object.greet_method()) # Output: Hello, Bob!

In this example:

  • greet_function is a function that takes a name as an argument and returns a greeting message.Greeter is a class with a method

  • greet_method which doesn't explicitly take a name argument but accesses it through self, referring to the instance of the class.

Key differences highlighted in this example:

  • The function greet_function is standalone and can be called directly by its name.

  • The method greet_method is associated with the Greeter class and is called using an instance of the class.

  • The method greet_method operates on the data (name) within the instance of the class (Greeter).