how to import a class from another file in python

When the program is very complex, we often divide it into chunks or modules and are saved into multiple files. This reduces the complexity and makes it easy to debug or identify errors in the code. Suppose you want to use a class that is in another file. For this, you need to import that class into the file where you want to use it.

In this tutorial, we are going to discuss some methods which are used to import classes. Importing classes from other programs allows us to use them within the current program. Thus, helping in improved readability and reusability of code. Importing can be done within the same or from different folders.

If you want to learn more about python Programming, visit Python Programming Tutorials.

Some of the common ways to import a class from another file in Python are listed below

  • Import a specific class by using the import command.
  • Importing mulitple classes from one file using import command.
  • Import all classes from one file using import* command.
  • Import all classes from another folder in parent directory using Import Sys command.
  • Import a class dynamically.

Importing a specific class by using the import command

You just have to make another .py file just like MyFile.py and make the class your desired name. Then in the main file just import the class using the command line from MyFile import Square.

#Code starts here

MyFile.py
class Square:
   def __init__(self,val):
      self.val=val
   def getVal(self):
      return self.val*self.val

main.py
from MyFile import Square

newClass = Square(5)
val = newClass.getVal()

print(val)

#Code ends here
Output:
25

IMPORT MULTIPLE CLASSES FROM ONE FILE USING IMPORT COMMAND

When you have multiple classes in the MyFile.py. Then instead of writing import command with every class you just have to import the file that contains the classes and in the main.py file use these classes by making their respective objects.

#Code starts here

MyFile.py
class Square:
   def __init__(self,val):
      self.val=val
   def getVal(self):
      return self.val*self.val


class Add_Sub:
   def add(self, a, b):
      return a + b
   def sub(self, a, b):
      return a - b

main.py
import MyFile
# creating object for Square class
object1 = MyFile.Square(5)
print(f"From class Square: {object1.getVal()}")
# creating object for Add_Sub class
object2 = MyFile.Add_Sub()
print(f"From class Add_Sub: Addition {object2.add(2,3)}")
print(f"From class Add_Sub: Subtraction {object2.sub(2,3)}")

#Code ends here
OUTPUT:

From class Square: 25
From class Add_Sub: Addition 5
From class Add_Sub: Subtraction -1

IMPORT All CLASSES FROM ONE FILE USING IMPORT * COMMAND

Here you just have to write an asterisk (*)  with the import command i.e, import*. This command allows access to all the classes and you don’t need to write the name of the class with every function. You just have to make the object with that respective class.

#Code starts here

MyFile.py
class Square:
   def __init__(self,val):
      self.val=val
   def getVal(self):
      return self.val*self.val


class Add_Sub:
   def add(self, a, b):
      return a + b
   def sub(self, a, b):
      return a - b

main.py
from MyFile import *
# creating object for Square class
object1 = Square(5)
print(f"From class Square: {object1.getVal()}")
# creating object for Add_Sub class
object2 = Add_Sub()
print(f"From class Add_Sub: Addition {object2.add(2,3)}")
print(f"From class Add_Sub: Addition {object2.sub(2,3)}")

#Code ends here

Output:

From class Square: 25
From class Add_Sub: Addition 5
From class Add_Sub: Addition -1

IMPORT All CLASSES FROM ANOTHER FOLDER in parent directory USING IMPORT SYS COMMAND

Here Inner_Project is the folder that is holding the file of our classes. The main file is in another folder ‘Project2’ which is also the parent folder of the Inner_Project. Before importing we have to include the __init__.py file in the Inner_Project that will contain our classes to tell the interpreter that our Project is within the same package.

sys.path.insert(0,“..”) command tells the interpreter to look from the parent folder to take out the desired class.

Address: Application/Inner_Project/MyFile.py

MyFile.py
class Square:
   def __init__(self,val):
      self.val=val
   def getVal(self):
      return self.val*self.val


class Add_Sub:
   def add(self, a, b):
      return a + b
   def sub(self, a, b):
      return a - b

Address: Application/Project2/main.py

#Code starts here

main.py
import sys
sys.path.insert(0,"..")
from Inner_Project.MyFile import Square
object = Square(5)
print(object.getVal())

#Code ends here
OUTPUT:
25

IMPORTing A CLASS DYNAMICALLY

Here the __import__(module_name) command is used to import the module or file, whereas getattr()  command is used to get the attributes of the class.

#Code starts here

module.py
# class inside the module
class MyClass:
   def myclass(str):
      print(f"Hello How are you {str} ?")

Dynamic.py
class Dyclass:
    def __init__(self, module_name, class_name):

       module = __import__(module_name) # __import__ method used to getmodule
       my_class = getattr(module, class_name) #getting attribute by getattr() 
       my_class.myclass('Usman')

obj = Dyclass("module", "MyClass")

#Code ends here
OUTPUT:
Hello How are you Usman ?

Please let us know your valuable feedback.

Leave a Comment

Your email address will not be published.