类中的循环导入

时间:2017-08-22 16:23:53

标签: python python-3.x

假设我在两个文件中有两个类:

virtualenv envname
New python executable in /root/envname/bin/python2.7
Also creating executable in /root/envname/bin/python
Installing setuptools, pip, wheel...done.
[root@thrift-test ~]# source envname/bin/activate
(envname) [root@thrift-test ~]# pip install happybase
Collecting happybase
 Downloading happybase-1.1.0.tar.gz (40kB)
100% |ââââââââââââââââââââââââââââââââ| 40kB 1.9MB/s
Collecting six (from happybase)
Downloading six-1.10.0-py2.py3-none-any.whl

from Son import Son
class Mother:
    def __init__(self):
        self.sons = []
    def add_son(self, son: Son):
        self.sons.append(son)

加上主文件

from Mother import Mother
class Son:
    def __init__(self, mother: Mother):
        self.mother = mother
        mother.add_son(self)

显然,我有一个循环依赖。如何在不丢失类型提示的情况下处理这种行为?

1 个答案:

答案 0 :(得分:4)

您唯一的循环依赖项是类型提示,可以将它们指定为字符串:

# Mother.py
class Mother:
    def __init__(self):
        self.sons = []
    def add_son(self, son: 'Son.Son'):
        self.sons.append(son)

# Son.py
class Son:
    def __init__(self, mother: 'Mother.Mother'):
        self.mother = mother
        mother.add_son(self)

您可能仍需要import Motherimport Son;我不确定当前的分析工具是否足够智能以解决类型提示。 不要使用from次导入;那些在导入时强制解析模块内容。