如何将子模块中的类/函数导入到另一个中?

时间:2017-11-21 15:42:16

标签: python python-module

假设我有一个python模块,如下所示:

setup.py
tpkg/
    __init__.py
    module1.py
    module2.py

其中__init__.py是:

from .module1 import class1
from .module2 import class2

module1.py是:

from .module2 import class2

class class1(object):
    def __init__(self):
        self._who = "Class 1"

    def __str__(self):
        return "I'm {}".format(self._who)

    def otherclass(self):
        print(str(class2()))

module2.py是:

from .module1 import class1

class class2(object):
    def __init__(self):
        self._who = "Class 2"

    def __str__(self):
        return "I'm {}".format(self._who)

    def otherclass(self):
        print(str(class1()))

setup.py是:

from setuptools import setup

setup(name="tpkg",
      version="0.0.1",
      packages=["tpkg"])

因此,这两个模块都需要导入另一个模块中包含的类。

如果我安装此模块并尝试import tpkg我收到错误

In [1]: import tpkg
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-1-834a70240c6c> in <module>()
----> 1 import tpkg

build/bdist.linux-x86_64/egg/tpkg/__init__.py in <module>()

build/bdist.linux-x86_64/egg/tpkg/module1.py in <module>()

build/bdist.linux-x86_64/egg/tpkg/module2.py in <module>()

ImportError: cannot import name class1

所以,我的问题是,我应该如何将两个模块中的类相互导入?

更新这个问题与给定here略有不同,后者询问为什么循环导入存在问题,而不是如何解决循环导入问题,这就是我需要的。

2 个答案:

答案 0 :(得分:1)

从相对路径导入移至绝对路径并从from ... import...语法移至import ...(在模块文件中)应解决您的问题

__init__.py

from tpkg.module2 import class2
from tpkg.module1 import class1

module1.py

import tpkg.module2

class class1(object):
    def __init__(self):
        self._who = "Class 1"

    def __str__(self):
        return "I'm {}".format(self._who)

    def otherclass(self):
    print(str(tpkg.module2.class2))

module2.py

import tpkg.module1

class class2(object):
    def __init__(self):
        self._who = "Class 2"

    def __str__(self):
        return "I'm {}".format(self._who)

    def otherclass(self):
        print(str(tpkg.module1.class1))

测试:

>>> import tpkg
>>> c = tpkg.module1.Class1()
>>> c
< tpkg.module1.Class1 object at 0x10535ffd0>
>>> c.otherclass()
<class 'tpkg.module2.Class2'>
>>>

答案 1 :(得分:1)

您通常应该尝试避免循环依赖:

http://stackabuse.com/python-circular-imports/

否则您可以尝试本地导入

class class1(object):
def __init__(self):
    self._who = "Class 1"

def __str__(self):
    return "I'm {}".format(self._who)

def otherclass(self):
    from test2 import class2

    print(str(class2()))

test = class1()

test.otherclass()

class class2(object):
def __init__(self):
    self._who = "Class 2"

def __str__(self):
    return "I'm {}".format(self._who)

def otherclass(self):
    from test1 import class1
    print(str(class1()))