How To Import a Class from Another File in Python

How To Import A Class From Another File In Python.

In python it is crucial to learn how to import a class from another file, particularly as projects evolve in complexity. As codebases expand, it’s beneficial to organize code into modular components where each file represent a module or a related set of functionalities. This modular approach allows you to reuse code, making your programs more organized and easier to maintain. In Python, importing a class means making the functionality of that class available for use in your current script or module. In this article, we will explore multiple methods for importing classes from one file to another in Python, providing insights into effective code structuring and promoting best practices for scalable and maintainable projects.

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

Let’s discuss different methods to import classes, making your programs more efficient and easier to maintain.

1) Importing a class from one file to another

To import a specific class in Python, create a separate Python script file (e.g., MyFile.py) where you define the desired class. In your main Python script (e.g., main.py), import this class using the import command, specifying the file name and the class name.

First, create a file named MyFile.py with the following class definition:

# MyFile.py 

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

You can import Square class from main.py using this code:

# main.py 
from MyFile import Square 
newClass = Square(5) 
val = newClass.getVal() 
print(val) 

#Code ends here

Here, the Square class is imported from the MyFile.py, allowing you to create an instance of the Square class in your main script. Creating an instance of a class means to give values to the variables in that class. In this specific example, the value of 5 is passed as an argument to the Square class, which computes the square of the value using the getVal method. The resulting output will be:

Output:

25

This output represents the result of the computation which, in this case is 25, as computed by the getVal method defined within the Square class. By importing specific classes using the import command, you can effectively organize your code and use the functionalities defined in external files within your main Python script.

2) Import Multiple Classes From One File using import command

To import multiple classes from one file in Python, you can simply import the file containing the classes and then access those classes in your main script. Below is a detailed explanation along with a code demonstration:

Consider a file named MyFile.py that includes two classes, Square and Add_Sub.

# 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

To use these classes in another file, such as main.py, you can import the entire MyFile module and then create objects of the classes within MyFile.

# 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)}")

In the code snippet above, the MyFile module is imported, allowing you to create instances of the Square and Add_Sub classes. Consequently, you can call the respective methods belonging to these classes. When you run the main.py script, you will get the following output:

Output:

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

3) Import All Classes From One File Using Import * Command

When you want to import all classes from a specific file in Python, you can utilize the import * command. This particular command grants you access to all the classes within the target file without needing to specify each class name individually for every function. By using this method, you can create objects with the respective classes directly.

Consider the following demonstration:

#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
 

In the main file, main.py, you can use the import * command to access all the classes from MyFile.py:

# 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

Using the import* command can simplify the code structure by eliminating the need to specify individual class names, making it a convenient way to access and utilize multiple classes from a single file. However, it is important to exercise caution while using this method to prevent potential naming conflicts or unintended consequences in your code.

4) Importing a class From External Folders using Import SYS Command

When you need to import all classes from a different folder located in the parent directory, you can utilize the sys.path.insert(0, "..") command in Python. For this approach to work seamlessly, it is essential to include the __init__.py file in the folder that has the classes (referred to as Inner_Project in this example). This file signals to the interpreter that the current project is part of the same package.

The sys.path.insert(0, "..") command instructs the Python interpreter to traverse to the parent folder to retrieve the required class. Below is an example of how to implement this process, along with the associated file structures and code snippets.

File Structure

We can create a directory named Application and create two different folders in it. Lets name one folder Inner_Project and the other Project2. Now we need to keep MyFile.py in a different folder and main.py in a different folder.

  • Directory: Application/Inner_Project/MyFile.py
  • Directory: Application/Project2/main.py

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 hereAddress: Application/Project2/main.py

Output:

25

This script imports the Square class from the MyFile.py module located in the Inner_Project folder, which resides in the parent directory. The execution of this code yields an output of 25, which is the result obtained by invoking the getVal() method on an instance of the Square class.

By utilizing the sys.path.insert(0, "..") command along with the appropriate file structure and __init__.py file, you can seamlessly import classes from an external folder located in the parent directory.

5) Importing A Class Dynamically

Dynamically importing classes in Python is a powerful technique that allows you to load modules and access their attributes during runtime, enabling more flexible and adaptable programming. In this section, we will delve into a practical example that demonstrates the dynamic import of a class using the __import__ and getattr() functions.

Understanding the Process

To begin, consider a scenario where you have a module named module.py that contains a class called MyClass. The MyClass class, defined within the module.py file, includes a method myclass that prints a greeting message.

The implementation involves another file, Dynamic.py, which showcases how to dynamically import the MyClass from module.py and utilize its method myclass

#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 ?
  1. The __import__ function in Python is used to import a module or file dynamically during runtime. In the context of this example, it’s employed to import the module.py file.
  2. The getattr() function, also used in the Dynamic.py file, retrieves the attribute of the class specified as an argument. In this case, it retrieves the MyClass class from the dynamically imported module.
  3. After obtaining the class, the script calls the myclass method of the MyClass class with the parameter ‘Usman’, resulting in the printing of the greeting message ‘Hello How are you Usman ?’.

Utilizing dynamic class imports is particularly beneficial when you need to load classes based on user input or specific runtime conditions, enhancing the flexibility and adaptability of your Python applications.

Please let us know your valuable feedback.

Leave a Comment

Your email address will not be published. Required fields are marked *