When reading documentation or programming articles, we often see mentions of functions and methods. While they are similar concepts, they’re not the same. It is essential to understand what the difference is.
What is a function?Permalink
A function is simply a block (or chunk) of a code with a name.
If we want to execute the same code multiple times or from multiple places, we put it into function and then call it by its name.
def my_function(): print('hello') print('how are you?') my_function()
It might have parameters if we want to change the behaviour of the code in the function from the outside:
def my_function(name): print('Hello ' + name) print('How are you?') my_function('John')
What is a method?Permalink
A method is also a block (or chunk) of code with a name, and it can also have parameters. But there is one big difference between function and method:
A method is always associated with a class.
So when we talk about a method we talk about a method of a specific class and instances (objects) of that class.
Here is a method
my_method in class
class MyClass: def my_method(self): print('Hello from instance method')
The above method is called the instance method. In Python, instance methods always have at least one parameter named
self. When we call a method on an object Python will put the object the method is called on into this parameter, so we have access to it from within a method.
To call method
my_method, we first need to create an object from MyClass, and only then we can call the method:
obj = MyClass() obj.my_method()
We can also have static methods in Python. Static methods are associated with the class but do not need the object (instance) of that class. Hence they don’t have
class MyClass: @staticmethod def my_static_method(): print('I am static method')
To use a static method, we don’t have to create an object first:
But we can still call it on the objects of that class too:
obj = MyClass() obj.my_static_method()
So, the difference between functions and methods is the following:
- Methods are always associated with a class and objects of that class. We call methods on objects or classes.
- Functions are not associated with anything and can be called only by their names.
You might also like
Join the newsletter
Subscribe to get new articles about Python, code and programming into your inbox!