用Python导入包,属性错误 [英] Importing packages in Python, attribute error

查看:46
本文介绍了用Python导入包,属性错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python 新手,我正在尝试了解包和导入语句的工作原理.我制作了这个包,位于我的桌面:

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

这是包文件夹中 __ init __ .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")

在 subpackage1 文件夹中的 __ init __ .py 中:

and inside __ init __ .py in subpackage1 folder:

__ all __ =["module1"]

我想只写导入module1.py和module2.py

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

import package

在解释器中输入上面的命令后,我可以毫无问题地通过编写访问 module1.py 的任何功能

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()

其中 mod1() 是 module1.py 中定义的函数.但是当我输入

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

package.module2.mod2()

我收到AttributeError: module 'package' has no attribute 'module2'"(mod2() 是 module2.py 中定义的一个函数).这是为什么?提前谢谢你!

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

推荐答案

你得到 AttributeError 因为你没有在 __init__.py 中导入 module2 文件.

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

您不应该在 __init__.py 中执行 os.chdir() 来导入子模块.

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

我会这样做:

__ init __.pypackage 目录中.

from . import module2
from . import subpackage

__ init __.pysubpackage1 目录中.

from . import module1

这篇关于用Python导入包,属性错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆