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

1 投票
1 回答
2797 浏览
提问于 2025-04-19 21:10

我遇到了一个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 个回答

2

你可以通过不在导入时使用 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

撰写回答