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

How to Import Classes from Files within the Same or Subdirectory in Python?

Linda Hamilton
Release: 2024-11-26 15:13:09
Original
358 people have browsed it

How to Import Classes from Files within the Same or Subdirectory in Python?

Importing Classes within a Directory or Subdirectory

Question:

In a directory containing Python files, how can classes from specific files be imported into another file within the same directory or subdirectory?

Answer:

Python 2

  1. Create an empty __init__.py file in the same directory as the class files.
  2. Import classes using the regular import statement:

    from user import User
    from dir import Dir
    Copy after login

If the class files are in a subdirectory:

  1. Create an __init__.py file in the subdirectory as well.
  2. Use dot notation in the import statements:

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

Python 3

  1. Similar to Python 2, but prefix the module name with a . if not in a subdirectory:

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

The above is the detailed content of How to Import Classes from Files within the Same or Subdirectory in Python?. 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