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

2024-09-28 22:32:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我遇到了一个python导入循环问题。我不想把这两段代码合并成一个文件。我能做什么?在

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

在测试库.py公司名称:

^{pr2}$

在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")

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


Tags: infrompytestimport名称childobj
1条回答
网友
1楼 · 发布于 2024-09-28 22:32:57

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

在测试库.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公司名称:

^{pr2}$

相关问题 更多 >