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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3