簡體   English   中英

ModuleNotFoundError:運行代碼時沒有名為“包中的給定模塊”的模塊

[英]ModuleNotFoundError: No module named 'A given module in package' when running the code

這是完整的代碼:

MyApp/
            
     * mypkg/
              * __init__.py
              * mod1.py
              * mod2.py
     * Demo.py
      

我正在嘗試從 Demo.py 運行這個應用程序

mod1.py


class Person:
    def __init__(self,name,age,address):
        self.name = name
        self.age = age
        self.address = address

    def show_person(self):
        return "the name of the person is {0} and age is {1} ".format(self.name,self.age)

    

mod2.py

import mod1 as P

class Student(P.Person):
    def __init__(self,name,age,address,standard,grade):
        super(Student,self).__init__(name,age,address)
        self.standard = standard
        self.grade = grade

    def show_student(self):
        return "The name of the student is {0} and he is studing in {1} standard".format(self.name,self.standard)

__init__.py

__all__ = ["mod1","mod2"]

Demo.py

from mypkg import *

a = Person('John',12,'Near S School')
print(a.show_person())

b = Student('name', 17, 'Near X Resturant',12, 'B')
print(b.show_student())

output:

Traceback (most recent call last):
  File "d:\ROOT\WORK\Python\MyApp\Demo.py", line 1, in <module>
    from mypkg import *
  File "d:\ROOT\WORK\Python\MyApp\mypkg\mod2.py", line 1, in <module>
    import mod1 as P
ModuleNotFoundError: No module named 'mod1'

output 應該是一個帶有名稱和標准的字符串

例子:

學生的名字叫 Jhon,他正在學習標准 10。

mod2.py中,將導入更改為

import mypkg.mod1 as P

Demo.py中,將導入更改為

from mypkg.mod1 import Person
from mypkg.mod2 import Student

這應該允許您運行該程序。

暫無
暫無

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

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