Importing packages in Python, attribute error

让人想犯罪 __ 提交于 2020-01-24 13:15:29

问题


I'm new in Python and I'm trying to understand how packages and import statement work. I made this package, located in my Desktop:

package/
   __ init __.py
   module2.py
   subpackage1/
      __ init __.py
      module1.py

Here's what's inside __ init __ .py in the package folder:

__ all __ =["module2"]
import os
os.chdir("C:/Users/Leo--/Desktop/Package")
import subpackage1.module1
os.chdir("C:/Users/Leo--/Desktop")

and inside __ init __ .py in subpackage1 folder:

__ all __ =["module1"]

I want to import module1.py and module2.py by only writing

import package

After typing the command above into the interpreter I can access with no problems any function of module1.py by writing

package.subpackage1.module1.mod1()

where mod1() is a function defined in module1.py. But when I type

package.module2.mod2()

I get "AttributeError: module 'package' has no attribute 'module2'" (mod2() is a function defined in module2.py). Why is that? Thank you in advance!


回答1:


You get the AttributeError because you haven't imported the module2 in __init__.py file.

You shouldn't do os.chdir() in __init__.py to import submodules.

This is how I would do it:

__ init __.py in the package directory.

from . import module2
from . import subpackage

__ init __.py in the subpackage1 directory.

from . import module1


来源:https://stackoverflow.com/questions/45400529/importing-packages-in-python-attribute-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!