Difference between functions and Methods with examples.

Functions vs Methods

Difference between functions and Methods with examples.

Photo by Bram Naus on Unsplash

As a programmer, It is very important to know about Functions and Methods.

In programming, the terms “function” and “method” are often used interchangeably. However, there are fine-drawn differences between the two. Understanding these differences is important for writing efficient and effective code.

A function is a standalone block of code that performs a specific task. Functions are defined using the def keyword and can be called by their name followed by parentheses. They can take input in the form of arguments and can return output in the form of a return value. For example, consider the following function:

Here function, named ‘add’, takes in two arguments, a and b, and returns the sum of the two numbers.

On the other hand, a method is a function that is associated with an object or a class. In other words, it is a function that is defined within a class. Methods are called on an instance of a class by using dot(.) notation. For example :

In this example, the ‘add’ method is defined within the ‘MyClass’ class. An instance of the class ‘MyClass’ is created and the add method is called on it.

One of the key differences between functions and methods is that methods have access to the attributes and methods of the object or class they are associated with and can modify them. Functions do not have this capability.

In addition, methods can also be overridden, which means that a subclass can provide a different implementation for a method.

In conclusion, functions and methods are both important concepts in programming, but they have distinct differences. Functions are standalone blocks of code that perform a specific task, whereas methods are functions that are associated with an object or a class and have access to the attributes and methods of that object or class. Understanding these differences can help you write more efficient and effective code, and can also help you better understand the code of others so you can make a better decision on when and how to use them in your programming projects.

FunctionsMethods
It is a block of code with a nameIt is a part of an object and it represents the behavior of an object.
It can be invoked using the name of the function and passing parameters

Ex: len([1,2,3]) | can be invoked only on an object, using the dot operator without an object we cannot invoke a method
EX: [1,2,3].reverse() | | parameters are optional in the function | Methods must have at least one parameter called self |

That's it for Today. Thanks for your time.

Please share your valuable feedback by liking 👍, sharing🤝 and commenting.

#programming #python #functions #methods #learning

Did you find this article valuable?

Support CharanWrites by becoming a sponsor. Any amount is appreciated!