
When the program is very complex, we often divide it into chunks or modules which 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.
To import a class in Python, you can utilize the “import” keyword followed by the class name. For instance, to import the class “MyClass” from a module or file, simply use “import MyClass.” If you need to import “MyClass” from “module.py,” include the line “from module import MyClass” at the beginning of your script.
To import a class in Python, you can use the “import” keyword followed by the class name. For instance, to import the class “MyClass” from a module or file, simply write:
import MyClass
Alternatively, if you want to import “MyClass” specifically from “module.py,” use the following syntax at the beginning of your script:
from module import MyClass
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.
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 an 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 an object for Square class
object1 = MyFile.Square(5)
print(f"From class Square: {object1.getVal()}")
# Creating an 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 The 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.