The concept of a function is one of the most important in mathematics. A common usage of functions in computer languages is to implement mathematical functions. Such a function is computing one or more results, which are entirely determined by the parameters passed to it. Functions are a convenient way to divide your code into useful blocks, allowing us to order our code, make it more readable, reuse it and save some time. Also functions are a key way to define interfaces so programmers can share their code. Function is a piece of code written to carry out a specified task. To carry out that specific task, the function might or might not need multiple inputs. When the task is carried out, the function can or can not return one or more values.
There are two types of functions in Python:
Functions vs Methods
A method refers to a function which is part of a class. You access it with an instance or object of the class. A function doesn’t have this restriction: it just refers to a standalone function. This means that all methods are functions, but not all functions are methods.
Consider this following example, where you first define a function plus() and then a Summation class with a sum() method.
If you now want to call the sum() method that is part of the Summation class, you first need to define an instance or object of that class.
Remember that this instantiation not necessary for when you want to call the function plus()! You would be able to execute plus(1,2) simply by using print function.
Parameters vs Arguments
Parameters are the names used when defining a function or a method, and into which arguments will be mapped. In other words, arguments are the things which are supplied to any function or method call, while the function or method code refers to the arguments by their parameter names.
Consider the following example and look back to the above code: you pass two arguments to the sum() method of the Summation class, even though you previously defined three parameters, namely, self, a and b.
What happened to self?
The first argument of every class method is always a reference to the current instance of the class, which in this case is Summation. By convention, this argument is called self.
This all means that you don’t pass the reference to self in this case because self is the parameter name for an implicitly passed argument that refers to the instance through which a method is being invoked. It gets inserted implicitly into the argument list.