Functions and methods have a lot in common, actually, a method is literally a function that is associated with an object. This may be a little confusing especially for beginners and that is why in this article we will seek clarity on the distinction between functions and methods.
function vs method
By definition, a function is a collection of statements that can get executed together to perform a certain action. A method, on the other hand, is a special type of a function that is associated with a specific object or class.
The name 'function' is usually used to refer to standalone blocks of code that perform a specific task.
The add()
above is a standalone function, we would therefore use the name 'function' to refer to it rather than a method.Let us now consider an example with a method.
On the above example, we have a class named MyClass
, we have defined a "method" called add()
inside the class. In order to use the method, we had to instantiate an object of the class i.e obj
Some things to note about functions:
- A function does not need a class or an object.
- Functions are independent entities in a program.
- Functions do not require any mandatory arguments such as
self
. They take arguments based on the parameters specified in their declaration. - We can invoke a function by simply using its name.
- Functions are not associated with any objects.
Some things to note about methods:
- Methods are always bound to an object or a class.
- Methods are dependent on the class they belong to.
- To use a method we must pass through its class all the bound object.
- A method may need a mandatory first argument such as
self
orcls
.
As long as a function appears inside a class or we have to use another object in order to access it, we call it a method. There are three types of methods i.e instance, class and static methods you can follow the link to see more details about each of them.
Builtin functions and methods
Python comes with a number of builtin functions and methods.
Some common builtin functions includes print()
, len()
, min()
, max()
, etc
On the other hand, buitin methods are mostly associated with core data types such as lists, tuples , strings etc. Each data types have some methods associated with them that are relevant to them and can be used to manipulate its objects.