首页 > 解决方案 > '.' 的目的是什么?从另一个 py 文件导入类时?

问题描述

我创建了 2 个 Python 文件,并将其保存在OOP_1文件夹中。当我尝试运行时出现错误,我无法理解.从 Python 文件导入类时使用的目的。

我已经尝试从相关的 Python 文件中删除.student, .course,但它不会在main.py使用from OOP_1 import *.

  1. student.py

    class Student:
        def __init__(self,name, number):
            self._student_name = name
            self._student_number = number
    
  2. course.py

    from .student import Student
    
    class Course(Student):
        #instance attributes
        def __init__(self, name, code, credit, student_limit):
            # Your code for the constructor
            self._name = name
            self._code = code
            self._credit = credit
            self._student_limit = student_limit
    
  3. __init__.py

    from .student import Student
    from .course import Course
    
  4. main.py

    from OOP_1 import *
    

但是,在 中__init__,Python 给了我一个错误:

ModuleNotFoundError: No module named '__main__.student'; '__main__' is not a package

main.py中,Python 给了我:

ModuleNotFoundError: No module named 'course'

我可以做些什么来确保我存储课程的文件夹可以在main.py文件中工作?

标签: pythonpackagepython-module

解决方案


单个前导点表示相对导入,从当前包开始。

您需要在当前上下文中拥有这些模块才能像这样导入它们


推荐阅读