Python Import Class From Another File

  1. Python Import Class From Another File Using from and import Statements
  2. Python Import Class From Another File Using import and as Statements
  3. Python Import Class From Another File Using sys.path.insert() Method

This tutorial will explain various methods to import a class from another file in Python. We need to import a class from another file when we want to use methods of another class in our code. It saves time as we do not have to implement the methods again and makes the code looks clean as we do not have to copy-paste the methods in the current project.

Python Import Class From Another File Using from and import Statements

Suppose the class we want to import from a file is in some other folder. We can do it using from and import statements in two ways, either import file myfile from the folder myfolder, or import class myclass from myfolder.myfile. The two example codes below demonstrate both approaches to import a class from a file in Python.

Example Code 1:

from myfolder import myfile

class1 = myfile.myclass()

Example Code 2:

from myfolder.myfile import myclass

Python Import Class From Another File Using import and as Statements

Suppose we want to use the myfunction() method of the class myclass, which is in another file. We can use the function by importing myclass using import and as statements in Python. The example code below demonstrates how we can import a class from another file.

import myfolder.myfile as myModule
class1 = myModule.myclass()

Python Import Class From Another File Using sys.path.insert() Method

In case the required file of the class is in another folder, we can add that folder to the sys.path list, which Python searches to import the modules. Therefore, we will first have to add the folder to sys.path using the sys.path.insert() method and then import the file using the import statement.

The below example code demonstrates how to add a directory path to sys.path and import files in Python.

import sys
sys.path.insert(1, '/path/to/application/app/myfolder')

from myfile import myclass
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python Class

  • Get Class Name in Python