How to import the class within the same directory or sub directory?

In Python, you can use the import statement to import a module or class from a file within the same directory or a subdirectory.

To import a class from a file within the same directory, you can use the following syntax:

from filename import ClassName

For example, if you have a file named example.py in the same directory and it contains a class named ExampleClass, you can import it like this:

from example import ExampleClass

Watch a course Python - The Practical Guide

To import a class from a file within a subdirectory, you can use the following syntax:

from subdirectory.filename import ClassName

For example, if you have a file named example.py in a subdirectory named subdir and it contains a class named ExampleClass, you can import it like this:

from subdir.example import ExampleClass

You can also use import instead of from if you want to import the whole module and reference the class with the module name.

import subdir.example

subdir.example.ExampleClass()

You can also use importlib to import modules dynamically, in case you want to import module based on some condition or input.

import importlib

module = importlib.import_module("subdir.example")
example_class = getattr(module, "ExampleClass")

Please keep in mind that, in order to use import statement, the imported file should be in python path or in the same directory where the code is running.