In this tutorial, we are going to see the difference function vs method in Python Programming Language. Function and method have been interchangeable terms that many uses to explain a functionality. Whereas some languages don’t have the term functions while some don’t have the difference between a function and a method.
Difference between function vs method in Python is treated differently and having distinct concepts. In this article, we will go through with various examples that how function and method are different in python.
What’s a method? or method definition
A method cannot exist without an object calling to it. It refers to its object that invoke it and returns to it. A method is dependent on an object and is defined inside a class. When the class’s instance is created, you can call the method through that instance.
Here is a class defining a method
class dog: species="mammal" def beingCute(self,name): print(name, "is best at being cute")
We can call the method by created an object and referring it to the invoker.
doggo=dog () doggo.beingCute("maggy")
We can even have access to the variables in the class through the method without directly accessing it through the object. This is very useful in situations when the application cannot give direct access to variables, but indirect access through the method.
class dog: species="mammal" def beingCute(self,name): print(name, "is best at being cute") print("species is ",self.species)
Now use the method to display the variable “species”.
You can access any class attribute through the object if they are public and accessible.
In a method you must define the argument named “self” to give the reference of objects being created.
What’s is a function ? or function definition
A function is independent and is invoked by its name without explicit reference. You can define and call the function anywhere without the need of a class and a function object.
You don’t need to pass any “self” parameter and can even call the function with zero or more parameters.
def cat(name): print(name, "is best at sleeping") cat("crystal")
In python, we have user-defined functions and built-in functions. We have seen the examples of user-defined functions but what you haven’t noticed it that we have been using built-in function print(), input(), reverse() etc.
Thee built-in functions are those which have been defined by python and are reserved with their specific functionality. We just call them by their names. For some special functions we need to import their libraries accordingly.
Conclusion of function vs method in python
In other programming languages like C#, java, there is not a clear difference between method and function. There is a highlight simple key difference between function vs method in python and how they serve a purpose with their uniqueness.
Some of Python Functions and Methods are: