[英]What is the correct way to import top level module?
我希望能够在另一个模块(更深一层)中引用顶级模块。 我的解决方案有效,但是我想知道这是否是最好的方法。 请建议至少使用python 2.4
在下面的例子中,我想导入base.py
在abc.py
。
这是简化的目录结构-
- test.py
- mymodule/
- base.py
- __init__.py
- meta/
- abc.py
- __init__.py
base.py
内容
class basec1:
def basec1f1(self):
print "base::C1::F1() called"
class basec2:
def basec2f1(self):
print "base::C2::F1() called"
abc.py
内容
from mymodule.base import basec1
def abcfn():
print "abcfn() called"
obj = basec1()
obj.basec1f1()
test.py
内容
import mymodule.meta.abc as abc
abc.abcfn()
这对我来说很好。 您可以放弃打包方法(即删除__init__.py
文件),而改用相对导入 ,但是老实说,我更喜欢您的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.