繁体   English   中英

如何将子模块中的类/函数相互导入?

[英]How to import classes/functions from submodules into one another?

假设我有一个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

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

更新此问题与此处给出的问题稍有不同, 在这里提出的问题是为什么循环进口存在问题,而不是我所需要的如何解决循环进口问题。

从相对路径导入更改为绝对路径,然后从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'>
>>>

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

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()))

暂无
暂无

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

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