Python Programming

Import a Class from Another file in Python: How to?

Import a Class from Another file in Python: How to?

Introduction

When a program is extremely complicated, it is frequently broken up into modules or pieces and saved in many files. This lessens the complexity and makes it simple to troubleshoot or find code errors. Let's say you wish to use a class from a different file. You must import the class into the file where you wish to use it in order to accomplish this.

Importing a specific class by using import command

Simply create a new.py file that is identical to MyFile.py and give the class the name you want. Simply import the class using the command line argument MyFile import Square in the main file.

#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

write your code here: Coding Playground

Import multiple classes from one file using import command

When there are multiple classes in MyFile.py Instead of writing import commands for each class, simply import the file containing the classes and use these classes in the main.py file by creating 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

write your code here: Coding Playground

Import all classes from one file using import command

Simply precede the import command with an asterisk (*), i.e. import*. This command grants access to all classes, and you do not need to include the class name with each function. You simply need to create an object with that 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

write your code here: Coding Playground

Import all classes from another folder in parent directory using import sys command

  • Inner Project is the folder that contains the files for our classes. The main file is located in a different folder called 'Project2,' which is also the parent folder of the Inner Project. Before importing, we must include the __init .py file in the Inner Project that will contain our classes in order to inform the interpreter that our Project is in the same package as the interpreter.
  • The sys.path.insert(0,"..") command instructs the interpreter to look in the parent folder for the desired class.

Application/Inner Project/MyFile.py is the location.

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

write your code here: Coding Playground

Importing a Class Dynamically

#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('Kshitij')

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

#Code ends here

Output:

Hello How are you, Kshitij ?

write your code here: Coding Playground

Conclusion

In this article, we talked about a few approaches for importing classes. We can use classes from other programs within the one we're using by importing them, enhancing the code's readability and usability in the process.