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): self.company = company self.model = model self.year = year def get_details(self): details = str(self.year) + ' ' + self.company + ' ' + self.model return details
Inside main.py write the following code:
from car import Car
Now, you can create a variable.
mycar = Car('Ford', 'Escort', 2000) print(mycar.get_details())
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 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.
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) print(myplane.get_details())