How To Call A Class Function From Another File In Python

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.

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”.

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.

Full Code:

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.