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 exampledef greet_function(name):return "Hello, {}!".format(name)# Method exampleclass Greeter:def __init__(self, name):self.name = namedef greet_method(self):return "Hello, {}!".format(self.name)# Using the functionprint(greet_function("Alice")) # Output: Hello, Alice!# Using the methodgreeter_object = Greeter("Bob")print(greeter_object.greet_method()) # Output: Hello, Bob!
In this example:
greet_functionis a function that takes anameas an argument and returns a greeting message.Greeteris a class with a methodgreet_methodwhich doesn't explicitly take anameargument but accesses it throughself, referring to the instance of the class.
Key differences highlighted in this example:
The function
greet_functionis standalone and can be called directly by its name.The method
greet_methodis associated with theGreeterclass and is called using an instance of the class.The method
greet_methodoperates on the data (name) within the instance of the class (Greeter).