[英]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.