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 |
Output:
25 |
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 |
Output:
From class Square: 25 |
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 |
Output:
From class Square: 25 |
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 |
Address: Application/Project2/main.py |
#Code starts here |
Importing a Class Dynamically
#Code starts here |
Output:
Hello How are you, Kshitij ? |
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.