Skip to content
Related Articles

Related Articles

How to import a class from another file in Python ?

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 30 Apr, 2021
Improve Article
Save Article

In this article, we will see How to import a class from another file in Python.

Import in Python is analogous to #include header_file in C/C++. Python modules can get access to code from another module by importing the file/function using import. The import statement is that the commonest way of invoking the import machinery, but it’s not the sole way. The import statement consists of the import keyword alongside the name of the module.

Getting Started

Here we have created a class named GFG which has two methods: add() and sub(). Apart from that an explicit function is created named method() in the same python file. This file will act as a module for the main python file.


class GFG:
    # methods
    def add(self, a, b):
        return a + b
    def sub(self, a, b):
        return a - b
# explicit function      
def method():

Let the name of the above python file be


It’s now time to import the module and start trying out our new class and functions. Here, we will import a module named module and create the object of the class named GFG inside that module. Now, we can use its methods and variables.


import module
# Created a class object
object = module.GFG()
# Calling and printing class methods
# Calling the function



Importing the module as we mentioned earlier will automatically bring over every single class and performance within the module into the namespace. If you’re only getting to use one function, you’ll prevent the namespace from being cluttered by only importing that function as demonstrated in the program below:


# import module
from module import method
# call method from that module  



In this way, we can use class to import from another file.

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!