How to import a class from another file in Python ?
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.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
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.
Let the name of the above python file be module.py.
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.
20 10 GFG
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:
In this way, we can use class to import from another file.