Python is a powerful programming language that is widely used in data science, web development, and other areas of computer science.
One of the key features of Python is its object-oriented programming paradigm, which makes it easy to write reusable code using classes and objects. In this tutorial, we will learn how to call a class function from another file in Python.
Steps:
Step 1: Create a Class in a File
The first step is to create a class in a file that we can call from another file. For this tutorial, let’s create a class called “Math” in a file called “mymath.py”. The class will have a function called “add” which will add two numbers and return the result.
1 2 3 |
class Math: def add(self, a, b): return a + b |
Step 2: Import the Class into Another File
The second step is to import the class “Math” in another file where we want to call its function. For this tutorial, let’s create a file called “main.py” and import the “Math” class from “mymath.py”.
1 |
from mymath import Math |
Step 3: Call the Class Function in Another File
The final step is to call the class function in the main file. To call a class function, we need to create an instance of the class and then call the function using that instance. For this tutorial, let’s create an instance of the “Math” class and call its “add” function with two numbers.
1 2 3 |
math = Math() result = math.add(2, 3) print(result) |
Full Code:
1 2 3 4 5 |
from mymath import Math math = Math() result = math.add(2, 3) print(result) |
The output of the above code will be:
5
Conclusion:
In this tutorial, we learned how to call a class function from another file in Python. We created a class with a function in one file and then imported and called that function in another file.
This technique allows us to write reusable code and make our programs more modular.