【问题标题】:What is the correct way to import top level module?导入顶级模块的正确方法是什么?
【发布时间】:2014-07-24 08:40:24
【问题描述】:

我希望能够在另一个模块中引用一个顶级模块(更深一层)。 我的解决方案有效,但我想知道这是否是最好的方法。请建议最低 python 2.4

在下面的示例中,我想在abc.py 中导入base.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()

【问题讨论】:

    标签: python


    【解决方案1】:

    这对我来说看起来不错。您可以放弃打包方法(即删除 __init__.py 文件)并改用 relative imports,但老实说,我更喜欢您的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-27
      • 2019-09-04
      • 2016-01-11
      • 2019-09-14
      相关资源
      最近更新 更多