【问题标题】:Python How Can I make base class file can import from child class filePython如何使基类文件可以从子类文件中导入
【发布时间】:2014-09-04 17:46:38
【问题描述】:

我遇到了一个 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")

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

【问题讨论】:

  • 这是最正常的做法。 . .但是,一般来说,基类不必知道它的子类的任何信息。强迫基地了解孩子的情况有点代码味道。
  • 不清楚你想要实现什么 - 你有两个文件试图相互导入,一个父类(也是?)与它的子类紧密耦合并且没有说为什么他们可以'不在一个文件中。
  • 对我来说听起来像是让你的子方法重载的工作。
  • 您应该阅读这篇关于导入 Python 模块的文章,尤其是关于 循环导入 effbot.org/zone/import-confusion.htm 的部分
  • @Thimble obj 可能是 child 、 list 或 dict 的实例。 child 可以使用 parent 的构造方法,因此我可以从不同类型的子实例(例如 childB 中的 childA)

标签: python class import importerror


【解决方案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

【讨论】:

  • 但是,你的问题是正确的:在你解决了你的设计问题之后,这个编码问题就消失了。
猜你喜欢
  • 2012-01-09
  • 2020-04-26
  • 1970-01-01
  • 1970-01-01
  • 2016-02-19
  • 2020-11-12
  • 1970-01-01
  • 1970-01-01
  • 2019-12-30
相关资源
最近更新 更多