[英]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 juice
。 from fruit.apple import juice
。
尝试:
from fruit.apple import juice as j
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.