This article covers the differences between functions and methods.
Before we proceed any further, please take a good look at the following piece of code. (It’s in python, but the general point remains the same and applies to all programming languages)
class test_class: def display(): print("Hello World, this is a method") def display(): print("Hello World, this is a function") test_class.display() display()
Chances are that you’ve already understood the difference. If you didn’t, don’t worry! That’s why we’re here.
While both have the exact same purpose, which is to execute a block of code, the difference is that a function is a standalone or independent piece of code. On the other hand, a method always belongs to a Class, or in more technical terms, it’s a member object of that particular Class.
Another way of describing the difference between the two is saying that a method is a function that is associated with a class.
Another thing you will have noticed, is how methods are called. As we mentioned earlier, methods are associated with classes. The
"." operator used between the class and method name is actually meant to represent this relationship.
Above is the general way calling a method. This really doesn’t have much to do with the differences between functions and methods, but it’s still useful to know.
If you’ve ever used third party libraries, such as
time you will have used the above format to call it’s methods. This is because you’re importing a class called
time which has many methods in it.
This is us calling the
sleep() method of the time class. Does it look familiar? By this point you should be able to look at this code and say,
time is the Class to which the
sleep() function belongs. And since it’s associated with a class, we’ll call it a method.
An interesting thing to note is that some languages (Java and C#) have only methods and some languages only have functions (C). C++ and Python however have the option to create both. The reason for this is that in Java and C#, all of your code is contained in a class whereas in Python and C++ we have the choice whether to create a class or not.
To sum up, they have the same purpose and functionality. There isn’t some deep complex difference between the two of them that completely separates the two.
In fact, it’s common enough for a method to sometimes to be referred to as a function (though not the other way around). However, it’s a sign of a good programmer that they can correctly label a method as a method and a function as a function.
This marks the end of the Functions and methods article. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the article content can be asked in the comments section below.