In this Tutorial, we are going to discuss How can I call a function within a class? In PythonFunction call is an initiation for a function to execute and get the desired output on giving an appropriate argument as input.
What Is Function?
The function is a set of lines of code where that are designed for a specific purpose and created with the intention of reuse whenever it is needed by just calling and getting the answer on the requirement. Moreover, Functions have some specific range of execution.
Types Of Functions
There are two types of Functions in Python on the basis of declaration. We can declare the function as of our use and even there are a number of inbuild functions that we can directly use for our purpose.
In Build, functions are the functions where functions are already defined in the saved library of Python Where we can directly use them as per our requirement for example- pow(). We can directly call those functions. They are also reserved keywords which we can not use as variables name in any situations as it they are reserved in library.
This pow() function is an in-build function where we can directly use it as it is and get the power of two numbers
here given line means 3 to the power 2 which will result in 9.
There are many more such functions where we can directly use them and get the desired output
User Defined Function
They are the functions that a user defines for their own purpose and perform a certain set of calculations or operations. They are for specific purposes.
Calling of User-Defined Function
We have to call the user-define Functions, Which we can call either from the same class or a different class also by creating an object of the class where the function is defined.
Let’s take an example of calling a function from within the class
class MainClass: def first(self): print ("First function call") def second(self): self.first() print ("First and Second function call") class_instance = MainClass() class_instance.second()
Here in MainClass there are two functions That are First and second and here the second function called the first function where both the first and second are the function of the same class in MainClass.
So here it can clearly be seen how the object of the same class is calling the function in the same class.
We can Learn More about Function: Functions in Python
And also from: https://stackoverflow.com/questions/5615648/how-can-i-call-a-function-within-a-class