Home >Backend Development >Python Tutorial >How Do I Import Classes from the Same Directory or Subdirectory in Python?

How Do I Import Classes from the Same Directory or Subdirectory in Python?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-30 17:03:11931browse

How Do I Import Classes from the Same Directory or Subdirectory in Python?

Importing Classes from the Same Directory or Subdirectory in Python

In Python, you can import classes from files within the same directory or subdirectory by utilizing the __init__.py file. This file is an empty placeholder that indicates that the directory contains modules and packages.

Importing from the Same Directory

To import classes from files within the same directory as main.py, create an __init__.py file within that directory. Then import the classes using regular import statements:

from user import User
from dir import Dir

Importing from a Subdirectory

If the classes are located in a subdirectory, such as usr/user.py, you can first create an empty __init__.py file in the subdirectory. Then, in the main.py file, use dot notation to specify the subdirectory and class name:

from usr.user import User

Alternatively, in Python 3, you can prefix the module name with a dot to automatically append the current directory to the import path:

from .user import User

By utilizing the __init__.py file and proper import statements, you can import classes from within the same directory or subdirectory, enabling code reuse and modularity in your Python applications.

The above is the detailed content of How Do I Import Classes from the Same Directory or Subdirectory in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn