Python如何使基类文件可以从子类文件导入

时间:2014-09-04 17:46:39

标签: python class import importerror

我遇到了python导入循环问题。而且我不希望将两段代码合并到一个文件中。我该怎么办?

$ tree
.
├── testBase.py
└── testChild.py

testBase.py:

from testChild import Child

class Base(object):

    def __init__(self, obj):

        ## For some rease need detect obj
        if isinstance(obj,  Child):
            print("test")

testChild.py:

from testBase import Base

class Child(Base):

    def __init__(self):
        pass

错误:

$ python testChild.py
Traceback (most recent call last):
  File "testChild.py", line 1, in <module>
    from testBase import Base
  File "/cygdrive/d/Home/test_import/testBase.py", line 2, in <module>
    from testChild import Child
  File "/cygdrive/d/Home/test_import/testChild.py", line 1, in <module>
    from testBase import Base
ImportError: cannot import name Base

我可以像这样在运行时导入:

class Base(object):

    def __init__(self, obj):
        from testChild import Child
        ## For some rease need detect obj
        if isinstance(obj,  Child):
            print("test")

我想知道这是解决此问题的唯一方法吗?有一个好方法吗?

1 个答案:

答案 0 :(得分:1)

您可以通过避免在导入中使用from来避免收到错误消息:

testBase.py:

import testChild
class Base(object):
    def __init__(self, obj):
        ## For some rease need detect obj
        if isinstance(obj,  testChild.Child):
            print("test")

testChild.py:

import testBase
class Child(testBase.Base):
    def __init__(self):
        pass