繁体   English   中英

导入行为异常

[英]Strange behavior in import

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

 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 . import apple from . import apple fruit包装的__init__.py文件。 或者,您可以在同一位置使用from fruit import apple

嵌套软件包不会自动用作父软件包的属性,这仅在显式导入嵌套软件包之后才有效。

如果您首先import fruit.apple ,然后import fruit; fruit.apple import fruit; fruit.apple作品。 或者,您可以在fruit/__init__.py文件中明确导入apple嵌套包,以确保import fruit; fruit.apple import fruit; fruit.apple始终对您的fruit套餐用户有效。

apple包装中的juice模块也是如此。 您需要通过将其导入apple__init__.py使其可用。 from . import juice添加一个from . import juice from . import juice ,或使用绝对from fruit.apple import juicefrom fruit.apple import juice

尝试:

 from fruit.apple import juice as j

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM