【问题标题】:Python Import class error, trying to understand the root directory __init__.pyPython导入类错误,试图理解根目录__init__.py
【发布时间】:2017-06-06 14:44:07
【问题描述】:

我刚接触python 4 天。我只是想了解根 __init__.py 导入功能。谷歌搜索很多以理解相同但无法找到一个有用的链接(可能是我的搜索键不相关)。请分享一些链接。

我收到错误消息“ImportError: cannot import name Person”

下面是结构

Example(directory)
    model
        __init__.py (empty)
        myclass.py
    __init__.py
    run.py

myclass.py

class Person(object):
    def __init__(self):
        self.name = "Raja"

    def print_name(self):
        print self.name

__init__.py

from model.myclass import Person

运行.py

from model import Person

def donext():
    person = Person()
    person.print_name()

if __name__ == '__main__':
    donext()

【问题讨论】:

  • Person 不在model 中——它在model.myclass 中。您在__init__.py 中正确地进行了导入。为什么你在run.py 中的做法不同?
  • 为什么要加flask标签?
  • @john-gordon 在 run.py 中,我只是想从 _init_.py 导入并使用相同的
  • @gonczor 抱歉,已删除,因此不适用

标签: python python-2.7


【解决方案1】:

正如@gonczor 建议的那样,您可以简单地将 __init__ 留空(此外,您不需要根目录)并直接从包中导入:

from model.myclass import Person

或者,如果你有意将包的界面扁平化,就这么简单:

模型/__init__.py

from myclass import Person

运行.py

from model import Person

【讨论】:

    【解决方案2】:

    错误基本上是说解释器在给定的命名空间中找不到任何与Person 匹配的东西,在你的情况下是model 包。这是因为它在model.myclass 包中,但它被导入到root 而不是run

    python 中的模块基本上是带有__init__.py 脚本的目录。但是从 init 导入根级别的任何内容很棘手。而且,没有必要。

    好的,所以这意味着解决方案是直接从model 包导入,或者从rott 级别的__init__.py 导入。我会推荐前一种方法,因为它更常用。你可以这样做:

    from model.myclass import Person
    
    def donext():
        person = Person()
        person.print_name()
    
    if __name__ == '__main__':
        donext()
    

    并将__init__.py 留空。它们仅用于初始化,因此无需向它们导入所有内容。

    您可以在model/__init__.py 中添加一些内容,然后将其导入myclass.py,例如:

    __init__.py:

    something = 0
    

    myclass.py:

    from . import something
    print something
    

    【讨论】:

    • 感谢回复,学会了在子目录级别定义_init_.py声明并从你的代码中访问
    • 很高兴我能帮上忙 :)
    猜你喜欢
    • 1970-01-01
    • 2018-10-09
    • 2023-03-04
    • 1970-01-01
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-07
    相关资源
    最近更新 更多