Skip to main content
 首页 » 编程设计

python之导入中的奇怪行为

2025年05月04日12mfryf

我在导入模块时遇到问题。 如果我使用,

 import fruit as f 
 print f.apple.juice.CALORIES_INT 

这行得通。 和

 import fruit.apple.juice as j 
 print j.CALORIES_INT 

不起作用。它抛出 AttributeError: 'module' object has no attribute 'apple'。关于如何调试它有什么建议吗?

我的目录结构如下:

fruit   
--- __init__.py   
--- apple   
---------__init__.py   
--------- juice.py   
---------------CALORIES_INT is a variable declared here   
--- orange   
--------- __init__.py   
--------- shake.py   
---------------trying to access CALORIES_INT here by importing it.  

苹果是一个包。不过,我可以导入其他包。

请您参考如下方法:

您需要添加 from 。将 apple 导入到 fruit 包的 __init__.py 文件中。或者,您可以在同一位置使用 from fruit import apple。

嵌套包不会自 Action 为父包的属性提供,这仅在显式导入嵌套包后有效。

如果你先import fruit.apple,那么import fruit; fruit.apple 有效。或者您在 fruit/__init__.py 文件中显式导入 apple 嵌套包以确保 import fruit; fruit.apple 始终适用于您的 fruit 包的用户。

同样适用于apple包中的juice模块;您需要通过将其导入 apple 包 __init__.py 来使其可用;添加一个 from 。 import juice,或使用绝对导入,如 from fruit.apple import juice。