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 will have to set the current path to the location of the file because in Python we can only import a file from the current directory. Therefore, we will first set the current directory to the file’s location using the sys.path.insert() method and then import the file using the import statement.

The below example code demonstrates how to change the current directory path and import the file 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

  • Nested Class in Python