Friday, November 15, 2024
Google search engine
HomeLanguagesHow to import a class from another file in Python ?

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.

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.

Python




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


Let the name of the above python file be module.py.

Importing

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.

Python




import module
   
# Created a class object
object = module.GFG()
   
# Calling and printing class methods
print(object.add(15,5))
print(object.sub(15,5))
   
# Calling the function
module.method()


Output:

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:

Python




# import module
from module import method
   
# call method from that module  
method()


Output:

GFG

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

RELATED ARTICLES

Most Popular

Recent Comments