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

How to Import Python Classes from the Same Directory or Subdirectory?

Barbara Streisand
Release: 2024-11-26 08:31:09
Original
569 people have browsed it

How to Import Python Classes from the Same Directory or Subdirectory?

Importing Classes from the Same Directory or Subdirectory

Importing Python classes from within the same directory or subdirectory can be achieved using the following methods:

Importing from the Same Directory

  1. Create an empty file named __init__.py in the same directory as the Python files. This signifies to Python that the directory can be imported from.
  2. Use regular import statements to import the classes:
from user import User
from dir import Dir
Copy after login

Importing from a Subdirectory

  1. Create an __init__.py file in the subdirectory where the classes reside.
  2. Use dot notation in the import statements, with one dot for each level of the subdirectory:
from classes.user import User
from classes.dir import Dir
Copy after login

In Python 3, another option for importing from the same directory is to prefix the module name with a dot:

from .user import User
from .dir import Dir
Copy after login

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template