Import Class From Another File and Directory in Python

When creating a file, it a good way to keep them outside our main file. For this reason, we need to create other files inside the same directory or other directories.

In this lesson, I’ll show you how you can access classes from different files.

Import class from another file in the same directory

When you import a class from a file that is located in the same directory as the main file, you have indicated that in your main file.

Here’s what our class car looks like:

Inside main.py write the following code:

Now, you can create a variable.

This is the printed result.

2000 Ford Escort

Import class from a file in a different directory

Packages

The most Pythonic way to import classes from other directories is by using packages. Inside our directory, we have two additional subdirectories: air and water.

Inside the first directory, there is file plane.py with the class Plane.

Inside the directory, there is an __init__.py file. This file is essential in Python 2 and older versions of Python 3. It’s not necessary for Python 3.3 and newer. They offer Implicit Namespace Packages. This means that you are not required to create __init__.py files.

Use this code to import the class.

It shows the path to a file and imports the Plane class.

Now, you can create an object the same way as in the previous example.