Import the Class within the Same Directory - Python
Last Updated :
28 Apr, 2025
Python classes are the methods to use object-oriented programming in Python. Python allows to create classes in the main project we are working on or in a new file that only stores the class definition.
This article will explain how to import a class within the same directory or subdirectory in Python. For this article, one does not need any Python modules but, a version of Python 3. x.
In order to utilize directories in any Python project, it is necessary to have an __init__.py file which works as a router to work between multiple files in a project. If one imports a module without an __init__.py file, they will receive an error as given in the following section.
Importing classes without __init__.py
When we import classes from a directory/subdirectory without __init__.py file in those directories/sub-directories, the python interpreter will throw the following error:
ImportError: attempted relative import with no known parent package
Using the __init__.py file to import classes
>CLASS #directory name
main.py #main file
name.py #file in same directory containing 'name' class
>sub #sub-directory
emp.py #sub-directory with file emp.py containing 'employ' class
We will use this directory set up for demonstration purposes. Here, the parent directory CLASS has two files - main.py and name.py(contains name class), and a subdirectory sub which contains sub.py file which contains another class employ. Now we will show how to import classes from name.py and emp.py into the main.py file.
To avoid the ImportError we saw in the previous section, we have to create an empty __init__.py file in the directory/sub-directory containing the required class definition. So, in our demonstration folder, we need to create two empty __init__.py files; one in the parent directory CLASS and the other in the sub-directory sub.
The new directory structure would look like this:
>CLASS #directory name
__init__.py #init file for parent directory
main.py #main file
name.py #file in same directory containing 'name' class
>sub #sub-directory
__init__.py #init file for sub directory
emp.py #sub-directory with file emp.py containing 'employ' class
Following is the pictorial representation of the same.
project structureHere, we can see that CLASS is the main directory, the sub is a subdirectory containing __init__.py and emp.py while the rest of the files are in the main directory. Now, the contents of the class definition files are given below.
Note: All the __init__.py files are empty as they are only required by the python interpreter for syntactical reasons.
name.py
Python3
# class definition
class name():
def __init__(self, name):
self.name = name
def disp(self):
print(self.name)
emp.py
Python3
# class
class employ():
def __init__(self, employment):
self.employment = employment
def job(self):
print(self.employment)
Importing classes in main.py
In the main.py file, to import the other 2 files, we will use the following syntax.
Python3
# import from same directory
from <filename> import <classname>
# import from sub directory
from <sub-directory>.<filename> import <classname>
The main.py file used in the example is as follows.
Python3
# Description: Importing modules from same directory
from name import name
# Description: Importing modules from sub directory
from sub.emp import employ
per = name("John")
per.disp()
emp = employ("Software Engineer")
emp.job()
Here we use the from keyword to define the file from which we are importing a class method; then we import the class by following its name with the import keyword.
In the case of the classes that exist in a sub-directory, we use the dot (.) indexing method, which is,
<sub-dir>.<filename>
to define the file location and then import the required class from it.
Output:
outputNote: If the __init__.py file contains some other reference/definition for the imported classes, python will choose those over the ones in the parent directory and subdirectory.
Example 2:
In this example, we shall see how to import classes at multiple levels of the directory. Consider a situation where the class we need to import lies within a sub-directory, that itself resides inside a sub-directory. We will import a class that resides in a second-level sub-directory.
The directory structure is as follows:
structureWe have to import the class located inside the class_imp.py file into the main.py file. The class definition in class_imp.py is :
Python3
# class_imp.py
class Hello():
def __init__(self, name):
self.name = name
def alert(self):
print(f'Hello {self.name}!')
The driver program to import this class is as follows:
Python3
# main.py file
# importing the Hello class
from level_2.level_3.class_imp import Hello
person = Hello("Geeks")
person.alert()
Output:
output
Similar Reads
Python - Import from sibling directory
In this article, we will discuss ways to import files from the sibling directory in Python. First, create two folders in a root folder, and in each folder create a python file. Below is the dictionary tree: Directory Tree: root : | |__SiblingA: | \__A.py | |__SiblingB: | \__B.py In B.py we will crea
3 min read
Python - Import module outside directory
Modules are simply a python .py file from which we can use functions, classes, variables in another file. To use these things in another file we need to first import that module into that file. If the module exists in the same directory as the file, we can directly import it using the syntax import
4 min read
Python - Import from parent directory
In this article, we will learn how to Import a module from the parent directory. From Python 3.3, referencing or importing a module in the parent directory is not allowed, From the below example you can clearly understand this. In the parent directory, we have a subdirectory, geeks.py file and in th
5 min read
Using a Class with Input in Python
In this article, we will see how to take input using class in Python. Using a Class with Input in Python It is to be noted that while using class in Python, the __init__() method is mandatory to be called for declaring the class data members, without which we cannot declare the instance variable (da
2 min read
Copy a directory recursively using Python (with examples)
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Pythonâs standard utility modules. This module helps in automating process of copying and removal of files and directories.shutil.copytree() method recursively copies an entire
5 min read
Why import star in Python is a bad idea
Using import * in python programs is considered a bad habit because this way you are polluting your namespace, the import * statement imports all the functions and classes into your own namespace, which may clash with the functions you define or functions of other libraries that you import. Also it
3 min read
Python - Read file from sibling directory
In this article, we will discuss the method to read files from the sibling directory in Python. First, create two folders in a root folder, and one folder will contain the python file and the other will contain the file which is to be read. Below is the dictionary tree: Directory Tree: root : | |__S
3 min read
What is the use of Python -m flag?
Python, a versatile and widely used programming language, provides a plethora of features and command-line options to facilitate various tasks. One such option that might pique your interest is the -m switch. In this article, we will explore what Python -m is and how it can be used, accompanied by f
2 min read
Class method vs Static method in Python
In this article, we will cover the basic difference between the class method vs Static method in Python and when to use the class method and static method in python.What is Class Method in Python? The @classmethod decorator is a built-in function decorator that is an expression that gets evaluated a
5 min read
The Ultimate Guide to Data Classes in Python 3.7
This article discusses data classes in Python 3.7 and provides an introductory guide for data classes in Python 3.7 and above. Data Class is a new concept introduced in Python 3.7 version. You can use data classes not only as a knowledge container but also to write boiler-plate code for you and sim
4 min read