簡體   English   中英

'.' 的目的是什么? 從另一個 py 文件導入類時?

[英]What's the purpose of '.' when importing classes from another py file?

我創建了 2 個 Python 文件,並將其保存在OOP_1文件夾中。 嘗試運行時出現錯誤,無法理解使用. 從 Python 文件導入類時。

我嘗試從相關的 Python 文件中刪除.student.course ,但它不會使用from OOP_1 import *main.py中運行。

  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文件中工作?

單個前導點表示相對導入,從當前的 package 開始。

您需要在當前上下文中擁有這些模塊才能像這樣導入它們

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM