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:

class Car:
    def init(self, company, model, year): = company
        self.model = model
        self.year = year
    def get_details(self):
        details = str(self.year) + ' ' + + ' ' + self.model     
        return details

Inside write the following code:

from car import Car

Now, you can create a variable.

mycar = Car('Ford', 'Escort', 2000)

This is the printed result.

2000 Ford Escort

Import class from a file in a different directory


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 with the class Plane.

Inside the directory, there is an 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 files.

Use this code to import the class.

from air.plane import Plane

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.

myplane = Plane('Cessna', '350', 2005)